Shortest Distance to a Character

Given a string `s` and a character `c` that occurs in `s`, return an array of integers `answer` where `answer.length == s.length` and `answer[i]` is the distance from index `i` to the closest occurrence of `c` in `s`. The distance between indices `i` and `j` is `abs(i - j)`.

30:00

Shortest Distance to a Character
easy
Free written solution
Topics
Companies

Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of c in s. The distance between indices i and j is abs(i - j).

Example 1:
Input: {"s":"loveleetcode","c":"e"}
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Constraints:
  • 1≤s.length≤1041 \leq s.\text{length} \leq 10^4

  • s[i] and c are lowercase English letters.

  • It is guaranteed that c occurs at least once in s.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"loveleetcode","c":"e"}

answer has one slot per character of s (12 in all). Each slot needs the distance to the nearest 'e', which can be on its left or on its right.

→ pass 1: nearest on the left
← pass 2: nearest on the right

s, with every 'e' lit up

row 1: distance from the leftrow 2: from the rightrow 3: answer

0

l

1

o

2

v

3

e

4

l

5

e

6

e

7

t

8

c

9

o

10

d

11

e
i = -
prev = -
Variables
VariableValue
n12
ce
DepthFunction Call
Stack empty
0/27