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.
LeetCode-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.
Input: timePoints = ["23:59","00:00"]
Output: 1
Input: timePoints = ["00:00","23:59","00:00"]
Output: 0
timePoints[i]
is in the format “HH:MM”.
A few observations to make:
Here is a Java implementation of the approach:
public int findMinDifference(List<String> timePoints) {
int[] minutes = new int[timePoints.size()];
for (int i = 0; i < timePoints.size(); i++) {
String[] time = timePoints.get(i).split(":");
int hours = Integer.parseInt(time[0]);
int mins = Integer.parseInt(time[1]);
minutes[i] = hours * 60 + mins;
}
Arrays.sort(minutes);
int ans = Integer.MAX_VALUE;
for (int i = 0; i < minutes.length - 1; i++) {
ans = Math.min(ans, minutes[i + 1] - minutes[i]);
}
// compare the extreme time points
// considering the circular nature of the clock
return Math.min(
ans,
24 * 60 - minutes[minutes.length - 1] + minutes[0]
);
}
As mentioned above the overall time complexity of the solution will be governed by the sorting of the time points. Assuming there are $n$ time points, the time complexity of sorting the time points will be $O(n \cdot \log n)$.
We can improve the time complexity of the solution by using a bucket sort approach. Since the time points are in the range of $0 \rightarrow 24 * 60$ (post conversion to minutes), we can use a linear time complexity approach to sort the time points.
Refer to bucket sort algorithm for more details.
Be notified of new posts. Subscribe to the RSS feed.