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 a Character INPUT String s = "loveleetcode" l o v e l e e t c o d e 0 1 2 3 4 5 6 7 8 9 10 11 Target: c = "e" 'e' found at indices: [3, 5, 6, 11] Find min distance from each index to nearest 'e' Example: index 0 ("l") Distance to e[3] = |0-3| = 3 Nearest 'e' is at index 3 ALGORITHM STEPS 1 Left-to-Right Pass Track distance from last 'e' prev = -INF --> scan left to right dist[i] = i - prev 2 Right-to-Left Pass Track distance from next 'e' next = +INF <-- scan right to left dist[i] = next - i 3 Take Minimum Min of both passes result[i] = min(left, right) 4 Time: O(n) Two passes through string Complexity Analysis Time: O(n) | Space: O(1)* *excluding output array FINAL RESULT Distance Array: 3 2 1 0 1 0 0 1 2 2 1 0 l o v e l e e t c o d e Output: [3,2,1,0,1,0,0,1,2,2,1,0] Verification: Index 0 ('l'): dist to e[3] = 3 OK Index 4 ('l'): dist to e[3|5] = 1 OK Index 8 ('c'): dist to e[6] = 2 OK Index 9 ('o'): dist to e[11] = 2 OK All 'e' positions have dist = 0 OK Solution Valid Key Insight: Two-pass approach captures both directions efficiently. Left pass finds distance to previous 'e', right pass finds distance to next 'e'. Taking minimum gives shortest path to nearest occurrence. This avoids checking all 'e' positions for each character, reducing O(n*k) to O(n). TutorialsPoint - Shortest Distance to a Character | Optimal Two-Pass Solution
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