Shortest Distance to a Character — LeetCode 821 Python Solution

EasyArrayTwo PointersString
Problem
#821
Reading time
3 min

The problem

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 character c in s. The distance between two indices i and j is abs(i - j), where abs is the absolute value function.

Example

Input
s = "loveleetcode", c = "e"
Output
[3,2,1,0,1,0,0,1,2,2,1,0]
Explanation
The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).

Python solution

Python
class Solution:
    def shortestToChar(self, s: str, c: str) -> List[int]:
        n = len(s)
        ans = [n] * n
        pre = -inf
        for i, ch in enumerate(s):
            if ch == c:
                pre = i
            ans[i] = min(ans[i], i - pre)
        suf = inf
        for i in range(n - 1, -1, -1):
            if s[i] == c:
                suf = i
            ans[i] = min(ans[i], suf - i)
        return ans

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 821. Shortest Distance to a Character is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 821. Shortest Distance to a Character?
LeetCode 821. Shortest Distance to a Character is rated Easy on LeetCode.
What is the time complexity of LeetCode 821. Shortest Distance to a Character?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 821. Shortest Distance to a Character?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 821. Shortest Distance to a Character cover?
LeetCode 821. Shortest Distance to a Character is tagged Array, Two Pointers and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview