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
Street with Houses and Street Lightsl3o2v1e0๐Ÿ’กl1e0๐Ÿ’กHouses find nearest street lightDistance = 1 to right lightEach house calculates distance to nearest street light
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).
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
85.2K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen