LeetCode 1629: Slowest Key

ArrayString

Problem Description

Explanation:

To solve this problem, we need to iterate through the keys pressed and calculate the duration of each keypress. We will keep track of the longest duration and the lexicographically largest key with that duration. We will update these values as we iterate through the keys. Finally, we return the lexicographically largest key with the longest duration.

  1. Initialize variables maxDuration as 0 and maxKey as the first key pressed.
  2. Iterate through the keys pressed:
    • Calculate the duration of the current keypress.
    • If the current keypress duration is greater than maxDuration, update maxDuration and maxKey.
    • If the current keypress duration is equal to maxDuration, update maxKey with the lexicographically largest key.
  3. Return the maxKey.

Time Complexity:

The time complexity of this solution is O(n) where n is the number of keypresses.

Space Complexity:

The space complexity of this solution is O(1) as we are using a constant amount of extra space.

:

Solutions

class Solution {
    public char slowestKey(int[] releaseTimes, String keysPressed) {
        int n = releaseTimes.length;
        int maxDuration = releaseTimes[0];
        char maxKey = keysPressed.charAt(0);
        
        for (int i = 1; i < n; i++) {
            int duration = releaseTimes[i] - releaseTimes[i - 1];
            if (duration > maxDuration || (duration == maxDuration && keysPressed.charAt(i) > maxKey)) {
                maxDuration = duration;
                maxKey = keysPressed.charAt(i);
            }
        }
        
        return maxKey;
    }
}

Loading editor...