Formatted question description: https://leetcode.ca/all/539.html

539. Minimum Time Difference

Level

Medium

Description

Given a list of 24-hour clock time points in “Hour:Minutes” format, find the minimum minutes difference between any two time points in the list.

Example 1:

Input: [“23:59”,”00:00”]

Output: 1

Note:

  1. The number of time points in the given list is at least 2 and won’t exceed 20000.
  2. The input time is legal and ranges from 00:00 to 23:59.

Solution

Sort the list timePoints. For each pair of adjacent time points (including the first and the last after sorting), calculate the difference between the two time points.

If the difference calculated by subtracting the smaller time point from the large time point is m minutes, then the minimum time difference between the two time points is Math.min(m, 1440 - m).

  • 1440 minutes = 24 hours * 60 min/h

Finally, return the minimum time difference among all time points.

class Solution {
    public int findMinDifference(List<String> timePoints) {
        Collections.sort(timePoints);
        int size = timePoints.size();
        int minDifference = difference(timePoints.get(0), timePoints.get(size - 1));
        for (int i = 1; i < size; i++) {
            int difference = difference(timePoints.get(i - 1), timePoints.get(i));
            minDifference = Math.min(minDifference, difference);
        }
        return minDifference;
    }

    public int difference(String timePoint1, String timePoint2) {
        int hour1 = Integer.parseInt(timePoint1.substring(0, 2));
        int minute1 = Integer.parseInt(timePoint1.substring(3));
        int hour2 = Integer.parseInt(timePoint2.substring(0, 2));
        int minute2 = Integer.parseInt(timePoint2.substring(3));
        int difference = Math.abs((hour2 - hour1) * 60 + (minute2 - minute1));
        return Math.min(difference, 1440 - difference);
    }
}

All Problems

All Solutions