Leetcode 539. Minimum Time Difference
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.
After assuming or asking for these clarifications, let’s proceed with the solution.
Here is the Java solution for the problem:
import java.util.*;
public class Solution {
public int findMinDifference(List<String> timePoints) {
int n = timePoints.size();
int[] minutes = new int[n];
// Convert each timePoint to minutes since 00:00
for (int i = 0; i < n; i++) {
String time = timePoints.get(i);
String[] parts = time.split(":");
int hours = Integer.parseInt(parts[0]);
int mins = Integer.parseInt(parts[1]);
minutes[i] = hours * 60 + mins;
}
// Sort the array of minutes
Arrays.sort(minutes);
// Compute the minimum difference
int minDiff = Integer.MAX_VALUE;
for (int i = 1; i < minutes.length; i++) {
int diff = minutes[i] - minutes[i - 1];
minDiff = Math.min(minDiff, diff);
}
// Wrap-around difference (last and first time point)
int wrapAroundDiff = (1440 + minutes[0] - minutes[n - 1]) % 1440; // ensuring non-negative difference
minDiff = Math.min(minDiff, wrapAroundDiff);
return minDiff;
}
public static void main(String[] args) {
Solution solution = new Solution();
List<String> timePoints = Arrays.asList("23:59", "00:00");
int result = solution.findMinDifference(timePoints);
System.out.println(result); // Should print 1
}
}
n
is the number of time points.Hence, the overall time complexity is O(n log n), where n
is the number of time points.
This solution is optimal and works efficiently within the permissible bounds of typical input sizes for such interview problems.
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?