Shortest Distance to a Character

EasyArrays & Hashingtwo pass

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a string s and a single character c that is guaranteed to appear at least once in s. Return an integer array answer of the same length as s, where answer[i] is the distance from index i to the nearest occurrence of the character c in the string. The distance between two indices i and j is defined as abs(i - j). In other words, for every position in the string, find how many steps (left or right) you must move to reach the closest position that holds the character c. A position that already holds c has a distance of 0.

Examples

Input: s = "loveleetcode", c = "e"
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
The character 'e' occurs at indices 3, 5, 6, and 11. For index 0, the closest 'e' is at index 3, so the distance is 3. For index 4, the nearest 'e' is at index 3 or 5, both distance 1.
Input: s = "aaab", c = "b"
Output: [3, 2, 1, 0]
The only 'b' is at index 3, so each earlier index measures its distance from index 3.
Input: s = "abbbbbba", c = "a"
Output: [0, 1, 2, 3, 3, 2, 1, 0]
The character 'a' sits at both ends (indices 0 and 7). Middle positions take the smaller distance to whichever 'a' is closer.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of only lowercase English letters.
  • c is a lowercase English letter.
  • c is guaranteed to occur at least once in s.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.