[
sort
bucket sort
math
string
]
Leetcode 0539 Minimum Time Difference
Problem statement
https://leetcode.com/problems/minimum-time-difference/
Solution
One possible way is to transform our times to numbers between 0
and 24*60 - 1
and sort them, then choose the minimum difference between adjacent points and also do not forget about difference between maximum and 24 * 60
minus minimum.
Complexity
Time complexity will be O(n log n)
, space complexity O(n)
.
Code
class Solution:
def findMinDifference(self, timePoints):
times = sorted([int(x[:2])*60 + int(x[3:]) for x in timePoints])
return min(min(y-x for x, y in zip(times, times[1:])), times[0] + 1440 - times[-1])
Remark
We can also use optimization, that if we have > 24 * 60
times, by pigeonhole principle we need to return 0
. Also we can use bucket sort with O(24 * 60)
time and memory, which is more preferable for big data.