
Given a string s and a character c that appears at least once in s, compute an array where each element represents the shortest distance from that index to any occurrence of character c. The distance between indices i and j is defined as abs(i - j) (the absolute difference).
Input:
Output:
Explanation:
Input:
Output:
Explanation:
1 <= s.length <= 10⁴s[i] and c are lowercase English lettersc occurs at least once in sTo find the shortest distances efficiently:
Left-to-Right Scan
s while tracking the last seen position of c.i, compute i - lastSeen if lastSeen is not None.Right-to-Left Scan
c, and update the result at index i if nextSeen - i is smaller than the current value.This ensures each character's distance is minimized based on the closest 'c' either to its left or right.
This approach is optimal for large strings and avoids unnecessary lookups or nested iterations.
The Java solution provided outlines an efficient method to calculate the shortest distance from each character in a given string to a specific target character. The function distanceToChar takes a string and a character as input and returns an array of integers where each element represents the minimum distance to the nearest occurrence of the target character.
result of the same length as the input string, to store the distances.lastSeen to keep track of the last occurrence index of the target character.lastSeen whenever the target character is found and calculating the distance from the current index to lastSeen.result array using the Math.min method.This two-pass approach ensures that all possible directions are considered for determining the shortest distance to the target character, resulting in an efficient and comprehensive solution.
0 Comments
Be the first to comment and share your perspective with the community.