Button with Longest Push Time - Problem
Button with Longest Push Time

Imagine a child playing with a digital keyboard, pressing buttons in sequence. You need to determine which button took the longest time to press based on the timing of consecutive button presses.

You are given a 2D array events where each events[i] = [index_i, time_i] represents:
index_i: The button that was pressed
time_i: The exact time when it was pressed

The array is sorted by time in ascending order. Your task is to calculate the push duration for each button:
• For the first button: push time = time when pressed
• For subsequent buttons: push time = current time - previous time

Goal: Return the index of the button with the longest push time. If multiple buttons have the same longest time, return the button with the smallest index.

Example: If events = [[1,2],[2,5],[3,9]], then:
• Button 1: push time = 2
• Button 2: push time = 5-2 = 3
• Button 3: push time = 9-5 = 4
Button 3 has the longest push time, so return 3.

Input & Output

example_1.py — Basic Case
$ Input: events = [[1,2],[2,5],[3,9]]
Output: 3
💡 Note: Button 1: duration = 2 (first button), Button 2: duration = 5-2 = 3, Button 3: duration = 9-5 = 4. Button 3 has the longest duration of 4.
example_2.py — Tie Breaker
$ Input: events = [[3,4],[5,6],[2,8]]
Output: 2
💡 Note: Button 3: duration = 4, Button 5: duration = 6-4 = 2, Button 2: duration = 8-6 = 2. Buttons 3, 5, and 2 all have different durations, with button 3 having the maximum duration of 4.
example_3.py — Single Button
$ Input: events = [[5,10]]
Output: 5
💡 Note: Only one button pressed at time 10. Its duration is 10, so return button 5.

Constraints

  • 1 ≤ events.length ≤ 1000
  • events[i] = [indexi, timei]
  • 1 ≤ indexi, timei ≤ 105
  • timei < timei+1 for all valid i
  • All button indices in events are unique

Visualization

Tap to expand
Button Press TimelineTime →1t=2Duration2Current Max2t=5Duration35-2=33t=9Duration49-5=4Winner!Button 3Max Duration: 4💡 Key Insight: Process events sequentially, tracking maximum duration in real-timeTime: O(n) | Space: O(1)
Understanding the Visualization
1
First Button
Duration = timestamp (no previous button to compare with)
2
Subsequent Buttons
Duration = current_time - previous_time
3
Track Maximum
Keep track of button with longest duration, preferring smaller index for ties
Key Takeaway
🎯 Key Insight: We can solve this efficiently in a single pass by calculating durations on-the-fly and maintaining the maximum, eliminating the need for extra storage space.
Asked in
Google 25 Amazon 20 Meta 15 Microsoft 12
28.6K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen