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 pressed
  • releaseTimes - an array where releaseTimes[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 just releaseTimes[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
Keyboard Timing AnalysisTimeline: Keys pressed sequentially0258Key Press Durations:a: 2b: 3c: 3 โœ“Duration = 2-0 = 2Duration = 5-2 = 3Duration = 8-5 = 3Winner: Same duration as 'b' but 'c' > 'b'
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.
Asked in
Amazon 25 Microsoft 18 Google 12 Apple 8
24.7K 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