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:
Input: ["23:59", "00:00"]
Output: 1
Note:
Q: Can the list of time points include duplicates? A: Yes, duplicates are possible and should be handled appropriately.
Q: Should we consider time between consecutive days, given the 24-hour format? A: Yes. The smallest difference might span across midnight.
Now, let’s move on to the strategy and code.
Here’s the Python code implementing the above strategy:
def findMinDifference(timePoints):
# Convert a time string "HH:MM" to minutes past midnight
def toMinutes(timeString):
hours, minutes = map(int, timeString.split(':'))
return hours * 60 + minutes
# Convert all time points to minutes
minutesList = [toMinutes(time) for time in timePoints]
# Sort the list of minutes
minutesList.sort()
# Initialize the minimum difference to a large number
minDiff = float('inf')
# Iterate through the sorted list and find the minimum difference
for i in range(1, len(minutesList)):
minDiff = min(minDiff, minutesList[i] - minutesList[i - 1])
# Check the difference between the last and first time points (crossing midnight)
minDiff = min(minDiff, (minutesList[0] + 1440) - minutesList[-1])
return minDiff
# Example usage
timePoints = ["23:59", "00:00"]
print(findMinDifference(timePoints)) # Output: 1
Overall, the time complexity is dominated by the sorting step, making it O(n log n).
This solution is efficient and handles the edge cases such as the transition from “23:59” to “00:00” correctly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?