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.
1using System;
2using System.Collections.Generic;
public class SlowestKeyArray {
public char SlowestKeyWithArray(int[] releaseTimes, string keysPressed) {
int[] durations = new int[releaseTimes.Length];
durations[0] = releaseTimes[0];
for (int i = 1; i < releaseTimes.Length; i++) {
durations[i] = releaseTimes[i] - releaseTimes[i - 1];
}
int maxDuration = durations[0];
char result = keysPressed[0];
for (int i = 1; i < durations.Length; i++) {
if (durations[i] > maxDuration || (durations[i] == maxDuration && keysPressed[i] > result)) {
maxDuration = durations[i];
result = keysPressed[i];
}
}
return result;
}
public static void Main() {
SlowestKeyArray solution = new SlowestKeyArray();
Console.WriteLine(solution.SlowestKeyWithArray(new int[] { 12, 23, 36, 46, 62 }, "spuda"));
}
}
C# uses a standard array to compute and store durations before determining the key with the longest duration.