Leetcode 1629: Slowest Key

Problem Definition

Given a list of integers representing a set of timestamps, and a string of letters representing keys pressed corresponding one-to-one with the timestamps, return the key which was pressed for the single longest duration. -- Leetcode 1629

Input release_times: [Int], keys_pressed: String

Output ch: String


Solution

def slowest_key(release_times, keys_pressed):
   padded = [0] + release_times
   deltas = list(map(lambda a, b: b-a, padded, release_times))
   press_times = sorted(list(zip(deltas, keys_pressed)))

   return press_times[-1][1]

Explanation and Reasoning

  1. Create new list by prepending 0 to the release times

  2. Create new list from mapping a difference function

  3. Zip two lists together and sort them by values in the first list

My idea here was to convert the view of the data. What we want to do is run a series of transformations over the original input in a functional way. We begin by converting our data from a list of timestamps to a list of differences, such that each value corresponds to the length of a key press. Once we have these values, we zip the list together with the keys, and sort it in ascending order with comparisons done in the first list. This gives us list of (int, str) pairs, sorted in order of keypress time, allowing us to quickly return the key that was depressed for the longest time.


Tags: leetcode python


Copyright © 2021 Justin Chin
Powered by Cryogen
Theme by KingMob