A laptop keyboard is connected to a computer. The computer records which keys are pressed, at what times and for how long the keys are held down. This data is stored in two lists:
releaseTimes
: contains the times at which a key is released.keysPressed
: contains the corresponding keys that are pressed.We are interested in finding the key with the longest duration that was pressed. If there is a tie, we need to return the lexicographically larger key.
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypress durations are as follows:
- 'c' -> 9 (from 0 to 9)
- 'b' -> 20 (from 9 to 29)
- 'c' -> 20 (from 29 to 49)
- 'd' -> 1 (from 49 to 50)
The longest duration is '20' and the lexicographically largest key is 'c'.
releaseTimes
and keysPressed
are not of the same length?
releaseTimes
and keysPressed
are always of the same length.keysPressed
?
releaseTimes
and keysPressed
simultaneously.def slowestKey(releaseTimes, keysPressed):
max_duration = releaseTimes[0]
slowest_key = keysPressed[0]
for i in range(1, len(releaseTimes)):
current_duration = releaseTimes[i] - releaseTimes[i-1]
if current_duration > max_duration or (current_duration == max_duration and keysPressed[i] > slowest_key):
max_duration = current_duration
slowest_key = keysPressed[i]
return slowest_key
# Example usage:
releaseTimes = [9, 29, 49, 50]
keysPressed = "cbcd"
print(slowestKey(releaseTimes, keysPressed)) # Output: "c"
The strategy involves a single pass through the releaseTimes
and keysPressed
arrays. Given n
as the length of the input lists:
O(n)
O(1)
assuming the input list fits in memory since we’re only tracking a few extra variables for the maximum duration and corresponding key.This solution should efficiently handle up to the maximum constraints typically given in such problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?