Ctrl K

Distance to the Nearest Marker

Easy
You are given a string text and a letter mark that appears in text at least once. For every position i of the string, find how far away the nearest occurrence of mark is. The distance between positions i and j is |i - j|; if mark itself sits at position i, the distance is 0. Return a list of length len(text) whose i-th element is the distance for position i.
Example 1
text='banana', mark='n' → [2, 1, 0, 1, 0, 1]

The letter n sits at positions 2 and 4. Position 0 is two steps from the nearest n, position 3 is one step from either of them, and the last position 5 is one step back.

Example 2
text='zzzq', mark='q' → [3, 2, 1, 0]

The only q is at the very end, so the distances simply count down towards it: 3, 2, 1, 0.

Example 3
text='x', mark='x' → [0]
Constraints
  • 1 ≤ len(text) ≤ 10⁵
  • text and mark consist of lowercase English letters, and mark is a single letter
  • mark occurs in text
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRise and Fall Lineup EasyGlued from the First Words EasyFirst Mirror Word EasyA Subsequence of One Word Only MediumLongest Word by Crossing Out Medium
loading Python…
Input
text='banana', mark='n'
Expected
[2, 1, 0, 1, 0, 1]

Run checks the first 3 tests in your browser. Submit checks all 121 tests on the server, hidden ones included.