#821
Shortest Distance to a Character
EasyArrayTwo PointersStringTwo PointersSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass from left to right and then another from right to left, ensuring we find the closest 'c' efficiently. This reduces unnecessary checks and improves performance.
⚙️
Algorithm
5 steps- 1Step 1: Initialize an array 'answer' with the same length as 's'.
- 2Step 2: Loop from left to right, keeping track of the last seen index of 'c'.
- 3Step 3: For each index, calculate the distance from the last seen index of 'c'.
- 4Step 4: Loop from right to left, updating the answer with the minimum distance found.
- 5Step 5: Return 'answer'.
solution.py13 lines
1def shortestToChar(s, c):
2 answer = [0] * len(s)
3 last_position = float('-inf')
4 for i in range(len(s)):
5 if s[i] == c:
6 last_position = i
7 answer[i] = i - last_position
8 last_position = float('inf')
9 for i in range(len(s) - 1, -1, -1):
10 if s[i] == c:
11 last_position = i
12 answer[i] = min(answer[i], last_position - i)
13 return answerℹ
Complexity note: This complexity is achieved because we only traverse the string twice, making it linear in relation to the length of the string.
- 1Using two passes (left-to-right and right-to-left) allows us to efficiently find the closest character.
- 2Tracking the last seen index of the target character helps in minimizing distance calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.