Problem Description
Given a sequence of keys pressed and the corresponding release times, determine which key had the longest press duration. The duration of the very first key is its releaseTime, and for every subsequent key, it is the difference between its releaseTime and that of the previous key. In the event of a tie in duration, return the lexicographically largest key.
Key Insights
- The first key's duration is directly provided by releaseTimes[0].
- For every other key, the duration is calculated as releaseTimes[i] - releaseTimes[i - 1].
- Tracking the maximum duration and updating the result with lexicographic comparison when durations are equal ensures we get the correct answer.
- A simple iteration over the arrays is sufficient to solve the problem.
Space and Time Complexity
Time Complexity: O(n) where n is the number of keypresses. Space Complexity: O(1) since only a few variables are used.
Solution
We iterate through the releaseTimes list while simultaneously accessing the keys in keysPressed. For the first key, the duration is just its release time. For the following keys, the duration is computed as the difference between the current and previous release times. As we iterate, we maintain two variables: one to track the maximum duration encountered so far, and another to store the key corresponding to that duration. If we find a keypress that has a duration equal to the current maximum, we then check if its key is lexicographically larger than the one stored, and update accordingly. This approach ensures that we satisfy the condition for ties.