Problem Description
Given n bulbs in a row (numbered 1 to n) that start off, one bulb is turned on per day following the order given in the array bulbs (where bulbs[i] = x indicates that on day i+1 the bulb at position x is turned on). The goal is to determine the minimum day such that there exists a pair of turned on bulbs with exactly k bulbs (all still off) between them. If no such day exists, return -1.
Key Insights
- Preprocess the bulbs array into a days array where days[i] indicates the day the bulb at position i+1 is switched on.
- Use a sliding window of size k+2: the window’s left and right boundaries represent the two bulbs and the interval between should all turn on later.
- For each window, check that every bulb between the boundaries turns on later than both the left and right bulbs.
- Return the minimum maximum day for any valid window; if none exist, return -1.
Space and Time Complexity
Time Complexity: O(n * k) in the worst-case using the sliding window approach. More advanced data structures (e.g., segment trees or binary indexed trees) can achieve O(n log n). Space Complexity: O(n) for the additional days array.
Solution
The solution uses a transformation step to create a days array mapping bulb positions to the day they are turned on. Then, a sliding window of length k+2 is moved along the days array. For each window, we ensure that every bulb strictly between the two boundaries turns on later than both boundaries. If the condition holds, the answer is updated with the maximum of the turning on days at the boundaries (as that is the day when both boundary bulbs are already on). If the condition fails, reposition the window starting from the bulb that violated the rule.