Welcome to Subscribe On Youtube

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);
        }
    }
    
  • class Solution {
    public:
        int findMinDifference(vector<string>& timePoints) {
            int res = INT_MAX, n = timePoints.size();
            vector<int> nums;
            for (string str : timePoints) {
                int h = stoi(str.substr(0, 2)), m = stoi(str.substr(3));
                nums.push_back(h * 60 + m);
            }
            sort(nums.begin(), nums.end());
            for (int i = 1; i < n; ++i) {
                res = min(res, nums[i] - nums[i - 1]);
            }
            return min(res, 1440 + nums[0] - nums.back());
        }
    };
    
    
    // reference: https://www.cnblogs.com/grandyang/p/6568398.html
    class Solution {
    public:
        int findMinDifference(vector<string>& timePoints) {
            int res = INT_MAX, pre = 0, first = INT_MAX, last = INT_MIN;
            vector<int> mask(1440, 0);
            for (string str : timePoints) {
                int h = stoi(str.substr(0, 2)), m = stoi(str.substr(3));
                if (mask[h * 60 + m] == 1) return 0;
                mask[h * 60 + m] = 1;
            }
            for (int i = 0; i < 1440; ++i) {
                if (mask[i] == 1) {
                    if (first != INT_MAX) {
                        res = min(res, i - pre);
                    }
                    first = min(first, i);
                    last = max(last, i);
                    pre = i;
                }
            }
            return min(res, 1440 + first - last);
        }
    };
    
  • class Solution:
        def findMinDifference(self, timePoints: List[str]) -> int:
            if len(timePoints) > 24 * 60:
                return 0
            mins = sorted(int(t[:2]) * 60 + int(t[3:]) for t in timePoints)
            mins.append(mins[0] + 24 * 60) # make it a circle, linking 1st and last slot
            res = mins[-1]
            for i in range(1, len(mins)):
                res = min(res, mins[i] - mins[i - 1])
            return res
    
    ############
    
    class Solution(object):
      def findMinDifference(self, timePoints):
        """
        :type timePoints: List[str]
        :rtype: int
        """
        ans = 24 * 60
        times = [0] * len(timePoints)
        for i, time in enumerate(timePoints):
          h, m = map(int, time.split(":"))
          times[i] = h * 60 + m
    
        times.sort()
    
        for i in range(len(times) - 1):
          ans = min(ans, abs(times[i] - times[i + 1]))
        return min(ans, 1440 - abs(times[0] - times[-1]))
    
    
  • func findMinDifference(timePoints []string) int {
    	if len(timePoints) > 24*60 {
    		return 0
    	}
    	var mins []int
    	for _, t := range timePoints {
    		time := strings.Split(t, ":")
    		h, _ := strconv.Atoi(time[0])
    		m, _ := strconv.Atoi(time[1])
    		mins = append(mins, h*60+m)
    	}
    	sort.Ints(mins)
    	mins = append(mins, mins[0]+24*60)
    	res := 24 * 60
    	for i := 1; i < len(mins); i++ {
    		res = min(res, mins[i]-mins[i-1])
    	}
    	return res
    }
    
    func min(a, b int) int {
    	if a < b {
    		return a
    	}
    	return b
    }
    
  • function findMinDifference(timePoints: string[]): number {
        const mins = timePoints
            .map(item => Number(item.slice(0, 2)) * 60 + Number(item.slice(3, 5)))
            .sort((a, b) => a - b);
        const n = mins.length;
        let res = Infinity;
        for (let i = 0; i < n - 1; i++) {
            res = Math.min(res, mins[i + 1] - mins[i]);
        }
    
        const first = mins[0] + 24 * 60;
        const last = mins[n - 1];
        res = Math.min(res, first - last);
    
        return res;
    }
    
    

All Problems

All Solutions