To solve this problem, we need to compute the minimum distance from each character in a given string to the nearest occurrence of a specified character.
Approach
The approach involves two passes over the string:
- Left to Right Pass: Traverse the string from the start to the end. For each character, if it is the target character, record its position. For other characters, calculate the distance to the last encountered target character.
- Right to Left Pass: Traverse the string from the end to the start. For each character, if it is the target character, record its position. For other characters, update the distance to the minimum of the current distance (from the left pass) and the distance to the next encountered target character.
This two-pass method ensures that we efficiently compute the minimum distance for each character by considering both directions.
Solution Code
def shortestToChar(s: str, c: str) -> list[int]:
n = len(s)
dist = [n] * n # Initialize with a value larger than max possible distance
# Left to right pass
last = -n # To handle positions before the first occurrence of c
for i in range(n):
if s[i] == c:
last = i
dist[i] = 0
else:
dist[i] = i - last
# Right to left pass
last = 2 * n # To handle positions after the last occurrence of c
for i in range(n-1, -1, -1):
if s[i] == c:
last = i
dist[i] = 0
else:
dist[i] = min(dist[i], last - i)
return dist
Explanation
- Initialization: We start by initializing an array
distwith a value larger than the maximum possible distance (length of the string) to ensure any valid distance will be smaller. - Left to Right Pass: We keep track of the last position where the target character
cwas found. For each character, if it's notc, we compute the distance to the lastcand store it indist. - Right to Left Pass: We again track the last position of
cbut from the end. For each character, if it's notc, we update the distance to the minimum of the current value (from left pass) and the distance to the nextc(from the right).
This method efficiently computes the required distances in linear time, O(n), where n is the length of the string, making it optimal for large inputs.
Example: For s = "loveleetcode" and c = "e", the output is [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0], which is correctly computed using the two-pass approach.
This solution handles all edge cases, including when the target character is at the start, end, or appears multiple times in the string. It also works if the target character is the only character in the string.


作者声明:本文包含人工智能生成内容。