Minimum Time Difference Problem
Description
LeetCode Problem 539.
Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.
Example 1:
Input: timePoints = ["23:59","00:00"]
Output: 1
Example 2:
Input: timePoints = ["00:00","23:59","00:00"]
Output: 0
Constraints:
- 2 <= timePoints <= 2 * 10^4
- timePoints[i] is in the format "HH:MM".
Solution
Approach: Bucket the Minutes of the Day
Comparing every pair of time points takes O(n2) time. Sorting them would work in O(n log n), but there are only 24 · 60 = 1440 possible times, so we can do the sorting with a table instead.
- Convert each time to minutes after midnight:
"HH:MM"becomesHH * 60 + MM. - Mark it in a boolean array
seenof size 1440. If it is already marked, two time points are equal and the answer is0. - Scan the array from minute 0 to 1439. Once the times are in order, the closest pair is always two neighbors, so compare each marked minute with the previous marked one.
The step people forget is that the clock is a circle. The latest and the earliest time are also neighbors, across midnight: "23:59" and "00:00" are 1 minute apart, not 1439. So after the scan, also check first + 1440 - last, where first and last are the earliest and latest marked minutes.
A side effect of the table is that any list with more than 1440 time points must contain a duplicate, so step 2 returns 0 before the scan even starts.
Complexity: O(n + 1440) = O(n) time and O(1440) = O(1) space, where n is the length of timePoints.
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
minutes_per_day = 24 * 60
seen = [False] * minutes_per_day # seen[m]: some time point is m minutes after 00:00
for time in timePoints:
minute = int(time[:2]) * 60 + int(time[3:])
if seen[minute]:
return 0 # the same time appears twice
seen[minute] = True
# Scan the day in order: the closest pair is two neighboring times...
first = -1 # earliest time point
prev = -1 # previous time point in the scan
best = minutes_per_day
for minute in range(minutes_per_day):
if not seen[minute]:
continue
if prev == -1:
first = minute
else:
best = min(best, minute - prev)
prev = minute
# ...or the latest and the earliest, going past midnight.
return min(best, first + minutes_per_day - prev)
Now write it from memory
Close the write-up and solve it yourself against the tests.