LeetCode 0539. Minimum Time Difference Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0539. 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 1: Sorting

We notice that there can be at most 24 × 60 = 1440 distinct time points. Therefore, if the length of timePoints exceeds 1440, it implies there are duplicate time points, and we can return 0 early.

Next, we iterate through the list of time points and convert it into a list of minutes nums. For example, for the time point 13:14, we convert it into 13 × 60 + 14.

Then, we sort the list of minutes in ascending order and append the smallest time nums[0] plus 1440 to the end of the list. This step is to handle the special case of the difference between the maximum and minimum values.

Finally, we iterate through the list of minutes to find the minimum difference between any two adjacent times.

The time complexity is O(n log n), and the space complexity is O(n), where n is the number of time points.

PythonJavaC++GoTypeScriptRustSwift
class Solution: def findMinDifference(self, timePoints: List[str]) -> int: if len(timePoints) > 1440: return 0 nums = sorted(int(x[:2]) * 60 + int(x[3:]) for x in timePoints) nums.append(nums[0] + 1440) return min(b - a for a, b in pairwise(nums))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !