Skip to content
Problem 821 · LeetCode 821(opens in a new tab)

Shortest Distance to a Character

EasyArrays

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.

Try it on LeetCode(opens in a new tab)
  1. Check every copy of cO(n·k)
  2. Two passesO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 letters, all cVerdict
Check every copy of cO(n·k)
Fine when c is rare
Two passesO(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 prev at 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 = n on the right pass with a fixed 10,000 sentinel; use 2n so any real distance wins.

How to talk through it

  1. 1Clarify. Is c always in s? Is distance the index gap?
  2. 2Give the brute force. List the positions of c and take the smallest gap for each index. Say it can reach n².
  3. 3Split the question. The nearest copy is the closest one to the left or to the right; one sweep finds each.
  4. 4Code the two passes. Explain the sentinel for prev before the first copy is seen.
  5. 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?