Amazon Online Assessment (OA) - Slowest Key

Practice here: https://leetcode.com/problems/slowest-key/

Solution and Explanation

This question asks for the key with the largest duration releaseTimes[i] - releaseTimes[i - 1]. We can simply loop through each release time and calculate its difference to the previous time. If multiple characters have the same duration, we want to use the lexicographically largest.

1class Solution:
2  def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
3      slowest_key = 'a'
4      longest_duration = 0
5      n = len(keysPressed)
6
7      for i in range(n):
8          pressedTime = releaseTimes[i - 1] if i > 0 else 0
9          duration = releaseTimes[i] - pressedTime
10          if duration == longest_duration:
11              slowest_key = max(slowest_key, keysPressed[i])
12          elif duration > longest_duration:
13              slowest_key = keysPressed[i]
14              longest_duration = duration
15
16      return slowest_key
17
1class Solution {
2  public char slowestKey(int[] releaseTimes, String keysPressed) {
3      int n = releaseTimes.length;
4      char[] keys = keysPressed.toCharArray();
5      char ans = 'a';
6      int longestDuration = 0;
7      int pressedTime;
8      int duration;
9      for (int i = 0; i < n; i++) {
10          if (i == 0) {
11              pressedTime = 0;
12          } else {
13              pressedTime = releaseTimes[i - 1];
14          }
15          duration = releaseTimes[i] - pressedTime;
16          if (duration == longestDuration) {
17              if (ans < keys[i]) ans = keys[i];
18          } else if (duration > longestDuration) {
19              ans  = keys[i];
20              longestDuration = duration;
21          }
22      }
23      return ans;
24  }
25}
26
Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro
Favorite (idle)