Problem Description
Given a string s and a character c that is guaranteed to appear in s, return an array where each element at index i is the minimum distance from i to any occurrence of character c in s. The distance between two indices i and j is defined as abs(i - j).
Key Insights
- The problem can be solved efficiently with two passes through the string.
- In the first pass (left-to-right), track the distance from the last seen occurrence of c.
- In the second pass (right-to-left), update the distance using the next occurrence of c.
- This two-pass technique guarantees that every index gets the minimum distance from both directions.
- The solution leverages constant additional space (apart from the output array) and linear time complexity.
Space and Time Complexity
Time Complexity: O(n) where n is the length of string s, as we iterate over the string twice. Space Complexity: O(n) for the output array storing the distances.
Solution
The approach involves scanning the string twice with two pointers:
- In the first left-to-right pass, initialize a variable to store the most recent index where character c was encountered. For each index, calculate the distance from the current index to that last seen index. If c hasn't been seen yet, we can simulate an infinitely large distance.
- In the second right-to-left pass, reinitialize a variable to track the next occurrence of c. Update the distance at each index to be the minimum of the existing distance and the distance from the next occurrence.
- This two-pass approach ensures that each index's distance reflects the nearest occurrence of c.