Shortest Distance to a Character (LeetCode 821): Solution and Explanation
For every index of a string, find how far it is from the nearest occurrence of a given character c, and return those distances as an array.
Intuition
The direct approach collects every index of c and, for each position, scans that list for the closest one. With many occurrences that is O(n^2) in the worst case.
The nearest c to position i is either the closest one on its left or the closest one on its right. Nothing else can win.
The closest c on the left is easy to track while walking left to right: remember the last index where c appeared. Every position after it measures its left distance against that index.
Walking right to left with the same idea gives the right distance. Taking the minimum of the two answers the question for every index in two linear passes.
Approach: Two sweeps with a remembered position
- Create
answerof length n and setprev = -n, a position far to the left of the string. - Walk i from 0 to n - 1. If
s[i] == c, setprev = i. Storeanswer[i] = i - prev. - Set
prev = 2n, a position far to the right. - Walk i from n - 1 down to 0. If
s[i] == c, setprev = i. Storeanswer[i] = min(answer[i], prev - i). - Return
answer.
Step-by-step example
s = "loveleetcode", c = "e"
- Left pass: indices 0 to 2 have no 'e' before them, so they get the placeholders 12, 13, 14.
- Index 3 is 'e', so prev = 3. Index 4 gets 1. Indices 5 and 6 are 'e' and get 0. Indices 7 to 10 get 1, 2, 3, 4. Index 11 is 'e' and gets 0.
- Right pass from index 11: prev = 11. Index 10 gets min(4, 1) = 1, index 9 gets min(3, 2) = 2, index 8 gets min(2, 3) = 2, index 7 keeps 1.
- Index 6 is 'e', so prev = 6, and index 5 then prev = 5. Index 4 keeps 1.
- Index 3 sets prev = 3. Indices 2, 1, 0 get min(14, 1), min(13, 2), min(12, 3) = 1, 2, 3.
- The result is [3,2,1,0,1,0,0,1,2,2,1,0].
Code: Python, Java, C++
1class Solution:
2 def shortestToChar(self, s: str, c: str) -> List[int]:
3 n = len(s)
4 answer = [0] * n
5 prev = -n
6 for i in range(n):
7 if s[i] == c:
8 prev = i
9 answer[i] = i - prev
10 prev = 2 * n
11 for i in range(n - 1, -1, -1):
12 if s[i] == c:
13 prev = i
14 answer[i] = min(answer[i], prev - i)
15 return answer1class Solution {
2 public int[] shortestToChar(String s, char c) {
3 int n = s.length();
4 int[] answer = new int[n];
5 int prev = -n;
6 for (int i = 0; i < n; i++) {
7 if (s.charAt(i) == c) {
8 prev = i;
9 }
10 answer[i] = i - prev;
11 }
12 prev = 2 * n;
13 for (int i = n - 1; i >= 0; i--) {
14 if (s.charAt(i) == c) {
15 prev = i;
16 }
17 answer[i] = Math.min(answer[i], prev - i);
18 }
19 return answer;
20 }
21}1class Solution {
2public:
3 vector<int> shortestToChar(string s, char c) {
4 int n = s.size();
5 vector<int> answer(n, 0);
6 int prev = -n;
7 for (int i = 0; i < n; i++) {
8 if (s[i] == c) {
9 prev = i;
10 }
11 answer[i] = i - prev;
12 }
13 prev = 2 * n;
14 for (int i = n - 1; i >= 0; i--) {
15 if (s[i] == c) {
16 prev = i;
17 }
18 answer[i] = min(answer[i], prev - i);
19 }
20 return answer;
21 }
22};Time and space complexity
O(n)
Two passes over the string, each doing constant work per index.
O(1)
Apart from the output array, only prev and the loop index are stored.
Other approaches
List of positions with binary search (time O(n log k), space O(k))
Collect every index of c into a sorted list. For each i, binary search for the insertion point and compare the neighbours on both sides.
Multi-source BFS (time O(n), space O(n))
Push every index of c into a queue with distance 0 and expand to i - 1 and i + 1. It works but is heavier than two sweeps for a one-dimensional string.
Common mistakes
- Starting
prevat -1 or 0 in the left pass. Positions before the first c would get a small, wrong distance that the right pass may not fix. - Using a sentinel that is too close, such as n in the right pass.
2nguaranteesprev - i >= n, which is larger than any real distance. - Overwriting
answer[i]in the second pass instead of taking the minimum with the left distance. - Forgetting that the character c can appear many times in a row; each occurrence resets
prev.
Frequently asked questions
Why are two passes enough?
The nearest c is on the left or on the right of i. The first pass computes the exact left distance and the second pass computes the exact right distance, so their minimum is the answer.
Why do the sentinels -n and 2n work?
Any real distance is at most n - 1. Measuring against -n or 2n always gives at least n, so a side with no c can never be chosen as the minimum.
Can it be done in a single pass?
Yes. Walk left to right and, each time you meet a c, walk back over the indices after the previous c and fix their right distances. Every index is still touched a constant number of times, but the two-sweep version is simpler to get right.