Slowest Key

The problem is about finding the key with the longest duration pressed on a keyboard. We are given the times when keys were released and the sequence of keys pressed. The duration of each key press is the difference between the release time of the current key and the previous key.

Here’s a step-by-step solution:

  1. Initialize variables to track the longest duration and the corresponding key.
  2. Iterate through the releaseTimes and compute the duration of each key press.
  3. If the current duration is greater than the longest duration found so far or is equal to the longest duration but the current key is lexicographically larger, update the longest duration and corresponding key.
  4. Return the key with the longest duration.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
        # Initialize the longest duration and corresponding key
        longest_duration = releaseTimes[0]
        key_with_longest_duration = keysPressed[0]

        # Iterate through the release times starting from the second element
        for i in range(1, len(releaseTimes)):
            # Calculate the duration for the current key press
            current_duration = releaseTimes[i] - releaseTimes[i - 1]

            # Check if the current duration is greater than the longest duration found so far
            # or if the duration is the same but the current key is lexicographically larger
            if current_duration > longest_duration or (current_duration == longest_duration and keysPressed[i] > key_with_longest_duration):
                longest_duration = current_duration
                key_with_longest_duration = keysPressed[i]

        # Return the key with the longest duration
        return key_with_longest_duration

Example

For the input releaseTimes = [9,29,49,50], keysPressed = "cbcd", the method would return "c" since the keypresses for ‘b’ and ‘c’ both have a duration of 20, but ‘c’ is lexicographically larger.