You get a string s and a single letter c that shows up in s at least once.
Build an array ans of the same length as s. For each index i, ans[i] is how far i is from the nearest index holding c, counted as the absolute difference of the two indices.
Example 1
Input: s = "mississippi", c = "s" Output: [2, 1, 0, 0, 1, 0, 0, 1, 2, 3, 4] Why: the copies of s sit at 2, 3, 5 and 6
1 more example and the constraints
Example 2
Input: s = "zzzx", c = "x" Output: [3, 2, 1, 0] Why: the only x is at the end
Constraints
- 1 ≤ s.length ≤ 10,000
- s and c are lowercase English letters
- c appears in s at least once
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every copy of cO(n·k)
- Two passesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 letters, all c | Verdict |
|---|---|---|---|
| Check every copy of c | O(n·k) | Fine when c is rare | |
| Two passes | O(n) | Best; two sweeps, done |
n = length of s, k = how many times c appears.
Edge cases to test
- One letter. "y" with c = "y" gives [0].
- c only at one end. The other pass has nothing to offer, so the sentinel must lose every
min. - Every letter is c. The answer is all zeros.
- A tie. In "tacocat" the o is 1 away from both c letters; the distance is 1 either way.
Common mistakes
- Starting
prevat 0 or −1 on the left pass, which gives small wrong distances before the first copy of c. - Doing only the left pass and forgetting that a copy on the right may be closer.
- Using
prev = non the right pass with a fixed 10,000 sentinel; use 2n so any real distance wins.
How to talk through it
- 1Clarify. Is c always in s? Is distance the index gap?
- 2Give the brute force. List the positions of c and take the smallest gap for each index. Say it can reach n².
- 3Split the question. The nearest copy is the closest one to the left or to the right; one sweep finds each.
- 4Code the two passes. Explain the sentinel for
prevbefore the first copy is seen. - 5Test out loud. Run "zzzx" and "ooo" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?