Lv.1arraystringtwo-pointers
Distance to the Nearest Stop
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
road is a string of lowercase letters; cells marked with the character c are bus stops. For every index i, compute the
distance |i - j| to the nearest index j with road[j] == c, and return the distances in order. c appears in road at
least once.
Examples
| road | c | result |
|---|---|---|
"loveleetcode" | 'e' | [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] |
"aaab" | 'b' | [3, 2, 1, 0] |
"x" | 'x' | [0] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(road: string, c: char) → int[]
Constraints
-
road.length, lowercase English letters only cis a lowercase letter that appears inroadat least once
Expected complexity
- Time
- O(N)
- Space
- O(N)
Examples
| road | c | Expected |
|---|---|---|
"loveleetcode" | "e" | [3,2,1,0,1,0,0,1,2,2,1,0] |
"aaab" | "b" | [3,2,1,0] |
"x" | "x" | [0] |
Hint
Hint
The nearest stop is either the last one to the left or the first one to the right. One left-to-right pass gives the distance to the left stop, one right-to-left pass gives the distance to the right stop; take the minimum. Searching outward from every cell is when stops are rare and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1142 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 4 | verdict only |