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.
1function slowestKey(releaseTimes, keysPressed) {
2 let maxDuration = releaseTimes[0];
3 let result = keysPressed[0];
4 for (let i = 1; i < releaseTimes.length; i++) {
5 let duration = releaseTimes[i] - releaseTimes[i - 1];
6 if (duration > maxDuration || (duration === maxDuration && keysPressed[i] > result)) {
7 maxDuration = duration;
8 result = keysPressed[i];
9 }
10 }
11 return result;
12}
13
14console.log(slowestKey([12,23,36,46,62], "spuda"));
The JavaScript version, similar to its counterparts, uses a for loop to evaluate the duration of each key press and decides the resulting character based on predefined rules.
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;
using 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.