#3386
Button with Longest Push Time
EasyArrayHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal solution, we traverse the events list once, calculating the time taken for each button press in a single pass. This is efficient and avoids unnecessary comparisons.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dictionary to store the last press time for each button.
- 2Step 2: Loop through the events and calculate the time taken for each button press.
- 3Step 3: Update the maximum time and corresponding button index if the current time taken is greater.
solution.py16 lines
1def longest_push_time(events):
2 button_times = {}
3 max_time = 0
4 result_index = -1
5
6 for index, time in events:
7 if index not in button_times:
8 button_times[index] = time
9 else:
10 time_taken = time - button_times[index]
11 button_times[index] = time
12 if time_taken > max_time or (time_taken == max_time and index < result_index):
13 max_time = time_taken
14 result_index = index
15
16 return result_indexℹ
Complexity note: This complexity is linear because we only traverse the events list once, storing the last press time for each button.
- 1Each button's time is calculated based on its last press time.
- 2We need to track both the time taken and the button index efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.