Shortest Distance to a Character — LeetCode 821 Python Solution
- Problem
- #821
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(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.