A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.
You are given a string keysPressed of length n, where keysPressed[i] was the i-th key pressed in the testing sequence, and a sorted list releaseTimes
, where releaseTimes[i]
was the time the i-th key was released. Both arrays are 0-indexed, and they are of the same length.
The duration of a key press is the time between the key’s press and release. The tester wants to know the key of the keypress that had the longest duration. If there is a tie, the key with the lexicographically largest key should be returned.
Example:
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"
Output: "c"
Explanation: The keypress durations are as follows:
- Key "c" has duration 9 (pressed at time 0 and released at time 9).
- Key "b" has duration 20 (pressed at time 9 and released at time 29).
- Key "c" has duration 20 (pressed at time 29 and released at time 49).
- Key "d" has duration 1 (pressed at time 49 and released at time 50).
Therefore, the key pressed with the longest duration is "b", but "c" (another key with the same duration) lexicographically comes last.
Constraints:
releaseTimes.length == n
keysPressed.length == n
2 <= n <= 1000
1 <= releaseTimes[i] <= 10^9
releaseTimes[i] < releaseTimes[i+1]
keysPressed contains only lowercase English letters.
releaseTimes
guaranteed to be sorted and strictly increasing?
releaseTimes[i] < releaseTimes[i+1]
.n
is at least 2.keysPressed
)?
releaseTimes[0]
.releaseTimes[i] - releaseTimes[i - 1]
.The time complexity of the solution is O(n)
, where n
is the length of the releaseTimes
and keysPressed
. This is because we iterate through the input arrays only once.
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
char slowestKey(vector<int>& releaseTimes, string keysPressed) {
char slowestKey = keysPressed[0];
int maxDuration = releaseTimes[0];
for (int i = 1; i < releaseTimes.size(); ++i) {
int duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration == maxDuration && keysPressed[i] > slowestKey)) {
maxDuration = duration;
slowestKey = keysPressed[i];
}
}
return slowestKey;
}
};
This code implements the strategy outlined above by:
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?