#1629

Slowest Key

Easy
ArrayStringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can achieve a more efficient solution by calculating the duration in a single pass through the keysPressed and releaseTimes arrays, maintaining the maximum duration and corresponding key as we go.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize variables for maximum duration and the corresponding key.
  2. 2Step 2: Loop through the keysPressed and calculate the duration for each keypress.
  3. 3Step 3: Update the maximum duration and key based on the conditions of duration and lexicographical order.
solution.py11 lines
1def slowestKey(releaseTimes, keysPressed):
2    max_duration = 0
3    result_key = ''
4
5    for i in range(len(keysPressed)):
6        duration = releaseTimes[i] if i == 0 else releaseTimes[i] - releaseTimes[i - 1]
7        if duration > max_duration or (duration == max_duration and keysPressed[i] > result_key):
8            max_duration = duration
9            result_key = keysPressed[i]
10
11    return result_key

Complexity note: The complexity is O(n) because we only make a single pass through the keysPressed and releaseTimes arrays, calculating durations in constant time.

  • 1The key with the longest duration is prioritized, and in case of ties, the lexicographically larger key is chosen.
  • 2Understanding the relationship between keypress duration and release times is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.