Minimum Time Difference
Problem
Given a list of HH:MM 24-hour times, return the smallest minute difference between any two times.
timePoints = ["23:59","00:00"]1def find_min_difference(times):
mins = sorted(int(t[:2]) * 60 + int(t[3:]) for t in times)
best = 24*60 - mins[-1] + mins[0]
for i in range(1, len(mins)):
best = min(best, mins[i] - mins[i-1])
return best
function findMinDifference(times) {
const m = times.map(t => Number(t.slice(0, 2)) * 60 + Number(t.slice(3))).sort((a, b) => a - b);
let best = 1440 - m[m.length - 1] + m[0];
for (let i = 1; i < m.length; i++) best = Math.min(best, m[i] - m[i-1]);
return best;
}
class Solution {
public int findMinDifference(List times) {
int[] m = new int[times.size()];
for (int i = 0; i < m.length; i++) {
String t = times.get(i);
m[i] = Integer.parseInt(t.substring(0, 2)) * 60 + Integer.parseInt(t.substring(3));
}
Arrays.sort(m);
int best = 1440 - m[m.length - 1] + m[0];
for (int i = 1; i < m.length; i++) best = Math.min(best, m[i] - m[i-1]);
return best;
}
}
int findMinDifference(vector& times) {
vector m;
for (auto& t : times) m.push_back(stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3)));
sort(m.begin(), m.end());
int best = 1440 - m.back() + m.front();
for (int i = 1; i < (int)m.size(); i++) best = min(best, m[i] - m[i-1]);
return best;
}
Explanation
To compare times easily, we first turn each HH:MM into a single number: total minutes since midnight, computed as hours * 60 + minutes. Now everything is just integers.
Once the minute values are sorted, the two closest times must sit next to each other in the sorted order, so we only need to check neighboring gaps instead of every pair.
There is one catch: the clock is circular. The gap between the last time and the first time can wrap around midnight, so we also consider 1440 - last + first (1440 = minutes in a day).
We start best with that wrap-around gap, then walk through adjacent pairs, taking the minimum difference, and return it.
Example: ["23:59","00:00"] becomes [1439, 0], sorts to [0, 1439]. The adjacent gap is 1439, but the wrap gap is 1440 - 1439 + 0 = 1, so the answer is 1.