Sponsored
Sponsored
This approach involves two passe through the string:
c
. Calculate the distance from the current index to this recent c
.c
found on this traversal.This ensures each element in the result is the minimum distance to any occurrence of c
.
Time Complexity: O(n)
, where n
is the length of the string since we go through the string twice.
Space Complexity: O(1)
additional space for variables, aside from the output array.
1var shortestToChar = function(s, c) {
2 const result = new Array(s.length).fill(0);
3 let
JavaScript uses a similar logic, where an array representing the shortest distances is first filled with distances to the closest left c
during a first pass. A second backward pass adjusts these distances with the nearest right occurrence using Math.min
.