Shortest Distance to a Character - Problem

Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.

The distance between two indices i and j is abs(i - j), where abs is the absolute value function.

Input & Output

Example 1 — Basic Case
$ Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
💡 Note: Character 'e' appears at indices 3, 5, 6, and 11. For each position, find distance to nearest 'e'.
Example 2 — Single Character
$ Input: s = "aaab", c = "b"
Output: [3,2,1,0]
💡 Note: Character 'b' only appears at index 3, so distances are [3,2,1,0].
Example 3 — All Same Character
$ Input: s = "abaa", c = "a"
Output: [0,1,0,0]
💡 Note: Character 'a' appears at indices 0, 2, and 3. Each position finds nearest 'a'.

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
Shortest Distance to Character 'e'loveleetcode01234567891011Target 'e' found at indices: 3, 5, 6, 11321010012210Distance from each position to nearest 'e'Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Understanding the Visualization
1
Input
String 'loveleetcode' and target character 'e'
2
Find Target
Locate all occurrences of 'e' at indices 3, 5, 6, 11
3
Calculate
For each position, find distance to nearest 'e'
Key Takeaway
🎯 Key Insight: For each position, the closest target character is either the nearest one to the left or to the right
Asked in
Facebook 25 Google 20 Amazon 15
89.0K Views
Medium Frequency
~15 min Avg. Time
2.1K 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