↓Skip to main content
  1. LeetCode/

LeetCode 821: Shortest Distance to a Character

·2 mins· ·
LeetCode Easy Array Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-15

  • Submissions: Wrong Answer → Accepted

Approach
#

Each answer is the smaller of the distances to the nearest c on the left and on the right. Scan left to right remembering the last c seen, then right to left doing the same and taking the minimum. Before any c is seen, treat its position as infinitely far.

My Attempts
#

Attempt 1’s second pass (right to left) forgot the + 1 and also lacked the return, so it returned None; fixing both passed.

Solution
#

class Solution:
    def shortestToChar(self, s: str, c: str) -> List[int]:
        n = len(s)
        res = [0] * n
        last = float("-inf")
        for i in range(n):
            if s[i] == c:
                last = i
            res[i] = i - last
        last = float("inf")
        for i in range(n - 1, -1, -1):
            if s[i] == c:
                last = i
            res[i] = min(res[i], last - i)
        return res

Complexity
#

Time O(n), space O(n) (output).

Mistakes to Avoid
#

  • Scan both directions; one pass misses a closer c on the other side.
  • Distances carried from the right need + 1.

Interview Explanation
#

One left-to-right pass gives the distance to the nearest c on the left, a right-to-left pass the nearest on the right, and I keep the smaller. Time O(n).

Related

LeetCode 832: Flipping an Image
·2 mins
LeetCode Easy Array Two-Pointers Bit-Manipulation Matrix
LeetCode 832 note: reverse each row and invert its bits, which two pointers can do at once
LeetCode 844: Backspace String Compare
·2 mins
LeetCode Easy Two-Pointers String Stack Simulation
LeetCode 844 note: simulate backspaces with a stack; for O(1) space, walk from the end and count how many characters each # skips
LeetCode 819: Most Common Word
·2 mins
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 note: replace punctuation with spaces, lowercase, split, count, and pick the most frequent word not banned
LeetCode 806: Number of Lines To Write String
·2 mins
LeetCode Easy Array String
LeetCode 806 note: simulate writing, wrapping when the next letter would exceed 100; landing exactly on 100 stays on the line
LeetCode 748: Shortest Completing Word
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 748 note: count the plate’s letters in lowercase, then find the shortest word covering every count, taking the earliest on ties
LeetCode 680: Valid Palindrome II
·2 mins
LeetCode Easy Two-Pointers String Greedy
LeetCode 680 note: at the first mismatch the only options are deleting the left or the right character; check whether either remainder is a palindrome