Slowest Key solution and explanation
9 more videos on this problem
Leetcode 1629. Slowest KeyFraz · 3:54 · 2K views
Slowest Key | Leetcode 1629 | leetcode solutionEasyLeetcode · 7:33 · 2K views
1629. Slowest Key (Leetcode Easy)Programming Live with Larry · 4:59 · 1K views
Slowest Key | LeetCode 1629 | Theory + Python codeSai Anish Malla · 5:39 · 1K views
Slowest Key | Leetcode 1629 | Live coding session 🔥🔥🔥Coding Decoded · 5:00 · 897 views
Leetcode - Slowest Key (Python)Timothy H Chang · 3:55 · 556 views
1629. Slowest Key | LEETCODE EASYcode Explainer · 5:12 · 416 views
Slowest Key Leetcode 1629 || Coding Culture5 Minutes Code · 5:01 · 279 views
Amazon Coding Interview Question | Leetcode 1629 | Slowest KeyWorkWithGoogler · 5:24 · 255 views
Daily Leetcode #524: Sep 06, 2021 - 1629. Slowest KeyProgramming Live with Larry · 5:37 · 186 views
The problem
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 ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.
The tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.
Return the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.
Example 1:
Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd" Output: "c" Explanation: The keypresses were as follows: Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9). Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29). Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49). Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50). The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20. 'c' is lexicographically larger than 'b', so the answer is 'c'.
Example 2:
Input: releaseTimes = [12,23,36,46,62], keysPressed = "spuda" Output: "a" Explanation: The keypresses were as follows: Keypress for 's' had a duration of 12. Keypress for 'p' had a duration of 23 - 12 = 11. Keypress for 'u' had a duration of 36 - 23 = 13. Keypress for 'd' had a duration of 46 - 36 = 10. Keypress for 'a' had a duration of 62 - 46 = 16. The longest of these was the keypress for 'a' with duration 16.
Constraints:
releaseTimes.length == nkeysPressed.length == n2 <= n <= 10001 <= releaseTimes[i] <= 109releaseTimes[i] < releaseTimes[i+1]keysPressedcontains only lowercase English letters.
Approach overview
Problem Overview: You receive an array releaseTimes and a string keysPressed. Each index represents a key press event. The duration of a key press equals the difference between the current release time and the previous release time. The task is to find the key with the longest press duration. If multiple keys share the same duration, return the lexicographically largest key.
Approach 1: Using Temporary Array for Duration Calculation (O(n) time, O(n) space)
This approach explicitly computes the duration of each key press and stores it in a temporary array. The first duration is simply releaseTimes[0], since the first key starts at time 0. For every other index i, compute releaseTimes[i] - releaseTimes[i-1]. After building the duration array, iterate through it to track the maximum duration and update the corresponding key. If two durations are equal, compare characters and keep the lexicographically larger key. This method separates computation and evaluation, which can make debugging easier when you want to inspect intermediate values.
Since you process the input twice (once to compute durations and once to find the answer), the time complexity remains O(n). The additional array introduces O(n) extra space. This approach is useful when clarity or intermediate inspection is preferred over minimal memory usage.
Approach 2: Simple Iteration with Maximum Duration Tracking (O(n) time, O(1) space)
This is the optimal solution used in most interview settings. Instead of storing all durations, compute each duration on the fly while iterating through the input. Maintain two variables: the current maximum duration and the result key. For index 0, the duration is releaseTimes[0]. For every other index, compute releaseTimes[i] - releaseTimes[i-1] and immediately compare it with the current maximum.
If the new duration is greater than the maximum, update both the maximum and the result key. If the duration is equal, choose the lexicographically larger character using a direct character comparison. Because each element is processed once and no additional structures are allocated, the algorithm runs in O(n) time with O(1) space.
This solution mainly relies on simple iteration over an array and comparison of characters from a string. The key insight is that the duration of each press depends only on the previous timestamp, so storing all durations is unnecessary.
Recommended for interviews: The single-pass duration tracking approach is what interviewers expect. It demonstrates that you recognize the sequential relationship between timestamps and avoid unnecessary memory usage. Mentioning the temporary-array version first can show your reasoning process, but implementing the O(1) space solution highlights stronger problem-solving skills.
Approach 1: Simple Iteration with Maximum Duration Tracking
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.
def slowestKey(releaseTimes, keysPressed):
max_duration = releaseTimes[0]
result = keysPressed[0]
for i in range(1, len(releaseTimes)):
duration = releaseTimes[i] - releaseTimes[i - 1]
if duration > max_duration or (duration == max_duration and keysPressed[i] > result):
max_duration = duration
result = keysPressed[i]
return result
print(slowestKey([12, 23, 36, 46, 62], "spuda"))public class SlowestKey {
public char slowestKey(int[] releaseTimes, String keysPressed) {
int maxDuration = releaseTimes[0];
char result = keysPressed.charAt(0);
for (int i = 1; i < releaseTimes.length; i++) {
int duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration == maxDuration && keysPressed.charAt(i) > result)) {
maxDuration = duration;
result = keysPressed.charAt(i);
}
}
return result;
}
public static void main(String[] args) {
SlowestKey solution = new SlowestKey();
System.out.println(solution.slowestKey(new int[]{12, 23, 36, 46, 62}, "spuda"));
}
}#include <vector>
#include <string>
using namespace std;
char slowestKey(vector<int>& releaseTimes, string keysPressed) {
int maxDuration = releaseTimes[0];
char result = keysPressed[0];
for (int i = 1; i < releaseTimes.size(); ++i) {
int duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration == maxDuration && keysPressed[i] > result)) {
maxDuration = duration;
result = keysPressed[i];
}
}
return result;
}function slowestKey(releaseTimes, keysPressed) {
let maxDuration = releaseTimes[0];
let result = keysPressed[0];
for (let i = 1; i < releaseTimes.length; i++) {
let duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration === maxDuration && keysPressed[i] > result)) {
maxDuration = duration;
result = keysPressed[i];
}
}
return result;
}
console.log(slowestKey([12,23,36,46,62], "spuda"));#include <stdio.h>
#include <string.h>
char slowestKey(int* releaseTimes, int releaseTimesSize, char* keysPressed) {
int maxDuration = releaseTimes[0];
char result = keysPressed[0];
for (int i = 1; i < releaseTimesSize; ++i) {
int duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration == maxDuration && keysPressed[i] > result)) {
maxDuration = duration;
result = keysPressed[i];
}
}
return result;
}
int main() {
int releaseTimes[] = {12, 23, 36, 46, 62};
char keysPressed[] = "spuda";
printf("%c\n", slowestKey(releaseTimes, 5, keysPressed));
return 0;
}using System;
public class SlowestKeySolution {
public char SlowestKey(int[] releaseTimes, string keysPressed) {
int maxDuration = releaseTimes[0];
char result = keysPressed[0];
for (int i = 1; i < releaseTimes.Length; i++) {
int duration = releaseTimes[i] - releaseTimes[i - 1];
if (duration > maxDuration || (duration == maxDuration && keysPressed[i] > result)) {
maxDuration = duration;
result = keysPressed[i];
}
}
return result;
}
public static void Main() {
SlowestKeySolution solution = new SlowestKeySolution();
Console.WriteLine(solution.SlowestKey(new int[] { 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.
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: Using Temporary Array for Duration Calculation
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.
def slowestKeyWithArray(releaseTimes, keysPressed):
durations = [releaseTimes[0]] + [releaseTimes[i] - releaseTimes[i - 1] for i in range(1, len(releaseTimes))]
max_duration = durations[0]
result = keysPressed[0]
for i in range(1, len(durations)):
if durations[i] > max_duration or (durations[i] == max_duration and keysPressed[i] > result):
max_duration = durations[i]
result = keysPressed[i]
return result
print(slowestKeyWithArray([12, 23, 36, 46, 62], "spuda"))import java.util.Arrays;
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.charAt(0);
for (int i = 1; i < durations.length; i++) {
if (durations[i] > maxDuration || (durations[i] == maxDuration && keysPressed.charAt(i) > result)) {
maxDuration = durations[i];
result = keysPressed.charAt(i);
}
}
return result;
}
public static void main(String[] args) {
SlowestKeyArray solution = new SlowestKeyArray();
System.out.println(solution.slowestKeyWithArray(new int[]{12, 23, 36, 46, 62}, "spuda"));
}
}#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;
}function slowestKeyWithArray(releaseTimes, keysPressed) {
let durations = [releaseTimes[0]];
for (let i = 1; i < releaseTimes.length; i++) {
durations.push(releaseTimes[i] - releaseTimes[i - 1]);
}
let maxDuration = durations[0];
let result = keysPressed[0];
for (let i = 1; i < durations.length; i++) {
if (durations[i] > maxDuration || (durations[i] === maxDuration && keysPressed[i] > result)) {
maxDuration = durations[i];
result = keysPressed[i];
}
}
return result;
}
console.log(slowestKeyWithArray([12,23,36,46,62], "spuda"));#include <stdio.h>
#include <string.h>
char slowestKeyWithArray(int* releaseTimes, int releaseTimesSize, char* keysPressed) {
int durations[releaseTimesSize];
durations[0] = releaseTimes[0];
for (int i = 1; i < releaseTimesSize; ++i) {
durations[i] = releaseTimes[i] - releaseTimes[i - 1];
}
int maxDuration = durations[0];
char result = keysPressed[0];
for (int i = 1; i < releaseTimesSize; ++i) {
if (durations[i] > maxDuration || (durations[i] == maxDuration && keysPressed[i] > result)) {
maxDuration = durations[i];
result = keysPressed[i];
}
}
return result;
}
int main() {
int releaseTimes[] = {12, 23, 36, 46, 62};
char keysPressed[] = "spuda";
printf("%c\n", slowestKeyWithArray(releaseTimes, 5, keysPressed));
return 0;
}using 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"));
}
}This Python approach uses list comprehensions, which allows creating a dedicated list for durations, making the process clear and concise.
Time Complexity: O(n)
Space Complexity: O(n)
Approach 3: Default Approach
func slowestKey(releaseTimes []int, keysPressed string) byte {
ans := keysPressed[0]
mx := releaseTimes[0]
for i := 1; i < len(releaseTimes); i++ {
d := releaseTimes[i] - releaseTimes[i-1]
if d > mx || (d == mx && keysPressed[i] > ans) {
mx = d
ans = keysPressed[i]
}
}
return ans
}Complexity comparison
| Approach | Complexity |
|---|---|
| Simple Iteration with Maximum Duration Tracking | Time Complexity: O(n) |
| Using Temporary Array for Duration Calculation | Time Complexity: O(n) |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Using Temporary Array for Duration Calculation | O(n) | O(n) | When you want clearer step-by-step computation or need to inspect all durations separately. |
| Simple Iteration with Maximum Duration Tracking | O(n) | O(1) | Best general solution. Minimal memory usage and expected approach in interviews. |
Frequently asked questions
Is Slowest Key easy or hard?
Slowest Key is categorized as an Easy problem on LeetCode with an acceptance rate around 59%. The challenge mainly involves correctly computing durations and handling the lexicographical tie-breaking condition. It is commonly used as a warm-up problem for array iteration and string comparison.
Slowest Key Python/Java solution
In both Python and Java, the solution iterates through releaseTimes, computes the duration for each key press, and updates the maximum duration and result character. Character comparison handles tie-breaking when durations match. The implementation remains O(n) time and O(1) space in both languages.
How to solve Slowest Key in O(n)?
Iterate through releaseTimes and compute each key's press duration using the difference between consecutive timestamps. Track the maximum duration and the corresponding key while scanning the array. If two durations match, return the lexicographically larger character. Because the array is processed once, the algorithm achieves O(n) time complexity.
What is the best approach for Slowest Key?
The best approach is a single-pass iteration that tracks the maximum key press duration while scanning the input. For each index, compute the duration as releaseTimes[i] minus releaseTimes[i-1] (or releaseTimes[0] for the first key). Update the maximum duration and result key accordingly, breaking ties using lexicographical comparison. This solution runs in O(n) time and O(1) space.
Is Slowest Key asked at Google/Amazon/Meta?
Slowest Key is a typical easy-level array and string problem used in coding interviews to test basic iteration and comparison logic. Variants of duration tracking and event-based array problems have appeared in interviews at companies like Amazon and Google, especially for early interview rounds.
What data structure is used in Slowest Key?
The solution primarily uses an array for the release times and a string for the pressed keys. The algorithm performs sequential iteration and simple arithmetic to compute durations. No advanced data structures such as hash maps or heaps are required for the optimal solution.
What is the time complexity of Slowest Key?
The optimal solution runs in O(n) time because each key press is processed exactly once. Only constant-time operations are performed during the iteration, such as subtraction and character comparison. Space complexity is O(1) since no additional data structures are required beyond a few variables.
