Shortest Distance to a Character
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 neededProblem
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
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.