Slowest Key - Problem
Imagine you're testing a revolutionary new keyboard for a tech company! ๐น A tester pressed a sequence of n keys, one at a time, and you need to find which key took the longest time to press.
You're given:
keysPressed- a string where each character represents a key that was pressedreleaseTimes- an array wherereleaseTimes[i]is when the i-th key was released
Key Rules:
- The first key (index 0) was pressed at time 0
- Each subsequent key was pressed exactly when the previous key was released
- Duration of key i =
releaseTimes[i] - releaseTimes[i-1](or justreleaseTimes[0]for the first key)
Goal: Return the character of the key that had the longest duration. If there's a tie, return the lexicographically largest character (e.g., 'z' > 'a').
Example: If keys "abc" were pressed with release times [2, 5, 8], then durations are: a=2, b=3, c=3. Since 'c' > 'b' lexicographically, return 'c'.
Input & Output
example_1.py โ Basic Case
$
Input:
releaseTimes = [2,5,8], keysPressed = "abc"
โบ
Output:
"c"
๐ก Note:
Key durations: a=2 (0โ2), b=3 (2โ5), c=3 (5โ8). Both 'b' and 'c' have max duration 3, but 'c' > 'b' lexicographically.
example_2.py โ Single Key
$
Input:
releaseTimes = [5], keysPressed = "a"
โบ
Output:
"a"
๐ก Note:
Only one key 'a' with duration 5. It's automatically the answer.
example_3.py โ Clear Winner
$
Input:
releaseTimes = [1,3,10], keysPressed = "xyz"
โบ
Output:
"z"
๐ก Note:
Key durations: x=1, y=2 (3-1), z=7 (10-3). 'z' has the longest duration of 7.
Constraints
- 1 โค keysPressed.length โค 105
- releaseTimes.length == keysPressed.length
- 1 โค releaseTimes[i] โค 109
- releaseTimes is sorted in non-decreasing order
- keysPressed contains only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Timeline Setup
Keys are pressed sequentially, each starting when the previous ends
2
Duration Calculation
Calculate how long each key was held down
3
Find Winner
Track the key with longest duration, breaking ties lexicographically
Key Takeaway
๐ฏ Key Insight: We can solve this efficiently in one pass by calculating durations on-the-fly and immediately comparing with our current best answer, using lexicographical comparison for tie-breaking.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code