539. Minimum Time Difference
Description
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 1:
Input: timePoints = ["23:59","00:00"] Output: 1
Example 2:
Input: timePoints = ["00:00","23:59","00:00"] Output: 0
Constraints:
2 <= timePoints.length <= 2 * 104
timePoints[i]
is in the format "HH:MM".
Solutions
Solution: Math
- Time complexity: O(Max(n,24*60))
- Space complexity: O(24*60)
JavaScript
js
/**
* @param {string[]} timePoints
* @return {number}
*/
const findMinDifference = function (timePoints) {
const MAX_MINUTE = 24 * 60;
const n = timePoints.length;
const times = Array.from({length: MAX_MINUTE + 1}).fill(false);
let result = MAX_MINUTE;
let minTime = MAX_MINUTE;
for (let index = 0; index < n; index++) {
const [hour, minute] = timePoints[index].split(':');
const time = hour * 60 + +minute;
if (times[time]) return 0;
times[time] = true;
minTime = Math.min(time, minTime);
}
let previous = minTime;
for (let time = 1; time < times.length; time++) {
if (!times[time] || time === minTime) continue;
result = Math.min(time - previous, result);
previous = time;
}
const headTailDiff = minTime - previous + MAX_MINUTE;
return Math.min(result, headTailDiff);
};