Sponsored
Sponsored
This approach involves iterating through both releaseTimes
and keysPressed
to calculate the duration of each keypress. We'll track the maximum duration found so far and update our result each time we find a keypress with a longer duration. If two keypresses have the same duration, we choose the lexicographically larger key.
Time Complexity: O(n), where n is the length of the releaseTimes array. We iterate through the list once.
Space Complexity: O(1), as we only use constant extra space for variables.
1def slowestKey(releaseTimes, keysPressed):
2 max_duration = releaseTimes[0]
3 result = keysPressed[0]
4 for i in range(1, len(releaseTimes)):
5 duration = releaseTimes[i] - releaseTimes[i - 1]
6 if duration > max_duration or (duration == max_duration and keysPressed[i] > result):
7 max_duration = duration
8 result = keysPressed[i]
9 return result
10
11print(slowestKey([12, 23, 36, 46, 62], "spuda"))
Python's simplicity shines in this solution, utilizing straightforward iteration and conditional checks. Key comparison is made simple with Python's operator overloading for strings.
In this approach, we create a temporary array to store the duration of each key press. We then iterate over this array to find the maximum duration. This solution separates the concerns of calculation and comparison for more clarity.
Time Complexity: O(n)
Space Complexity: O(n) due to additional array usage.
1#include <vector>
#include <string>
using namespace std;
char slowestKeyWithArray(vector<int>& releaseTimes, string keysPressed) {
vector<int> durations(releaseTimes.size());
durations[0] = releaseTimes[0];
for (int i = 1; i < releaseTimes.size(); ++i) {
durations[i] = releaseTimes[i] - releaseTimes[i - 1];
}
int maxDuration = durations[0];
char result = keysPressed[0];
for (int i = 1; i < durations.size(); ++i) {
if (durations[i] > maxDuration || (durations[i] == maxDuration && keysPressed[i] > result)) {
maxDuration = durations[i];
result = keysPressed[i];
}
}
return result;
}
Utilizes C++ vectors to handle durations, making dynamic sizing easier and clean with the STL vector operations.