Problem Description
Given an array of events where each event is represented as [button index, time] and the array is sorted by time, determine the button that experienced the longest push duration. The first event's duration is its own time, and for every subsequent event, the duration is the difference between the current event's time and the previous event's time. In case of a tie, return the button with the smallest index.
Key Insights
- The events are already sorted by time; hence, a single pass solution is possible.
- The duration for the first event is the event time itself.
- For every subsequent event, the push time is computed as the time difference between the current event and the previous event.
- Track the maximum duration and update the corresponding button index, taking into account the tie-breaking rule (smallest index wins).
Space and Time Complexity
Time Complexity: O(n), where n is the number of events. Space Complexity: O(1), using constant extra space.
Solution
We use a single pass through the events array. First, initialize the maximum duration using the first event’s time and record its button index. Then, for each subsequent event, calculate the duration by subtracting the previous event's time from the current event's time. Update the maximum duration and associated button index when a longer duration is found. In case a duration equals the current maximum, update the button index only if the current button index is smaller than the existing one.