Shortest Distance to a Character - Problem
Imagine you're a robot moving along a string, and you need to find the shortest distance to your favorite character from every position!
Given a string s and a character c that appears at least once in s, return an array where each element represents the minimum distance from that position to the nearest occurrence of character c.
The distance between two positions i and j is simply |i - j| (absolute difference of their indices).
Example: For string "loveleetcode" and character 'e', the distances would be [3,2,1,0,1,0,0,1,2,3,4] because each position finds its nearest 'e' and calculates the distance.
Input & Output
example_1.py โ Basic case
$
Input:
s = "loveleetcode", c = 'e'
โบ
Output:
[3,2,1,0,1,0,0,1,2,3,4]
๐ก Note:
The character 'e' appears at indices 3, 5, 6, and 7. Each position calculates its distance to the nearest 'e'.
example_2.py โ Single character
$
Input:
s = "aaab", c = 'b'
โบ
Output:
[3,2,1,0]
๐ก Note:
Only one 'b' at index 3, so distances are calculated from all positions to index 3.
example_3.py โ Target at start
$
Input:
s = "abcde", c = 'a'
โบ
Output:
[0,1,2,3,4]
๐ก Note:
Target character 'a' is at the beginning, so distances increase linearly from left to right.
Constraints
- 1 โค s.length โค 104
- s[i] and c are lowercase English letters
- It is guaranteed that c occurs in s
Visualization
Tap to expand
Understanding the Visualization
1
Mark Street Lights
Identify positions where target character 'e' appears (street lights)
2
Forward Pass
Walk left to right, tracking distance from the last street light seen
3
Backward Pass
Walk right to left, updating distances if we find closer street lights behind
4
Final Distances
Each house now knows its distance to the nearest street light in either direction
Key Takeaway
๐ฏ Key Insight: Two passes capture all possibilities - every position is closest to a target either from the left or from the right, never both directions equally (except when distance is 0).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code