#539
Minimum Time Difference
MediumArrayMathStringSortingSortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
By sorting the time points and calculating differences between consecutive times, we can efficiently find the minimum difference. This takes advantage of the fact that the smallest difference will be between two adjacent times in a sorted list.
⚙️
Algorithm
4 steps- 1Step 1: Convert each time point from 'HH:MM' format to total minutes since midnight.
- 2Step 2: Sort the list of time points in ascending order.
- 3Step 3: Calculate the difference between each pair of consecutive time points and keep track of the minimum difference.
- 4Step 4: Also check the difference between the last and first time point to account for the wrap-around.
solution.py14 lines
1# Full working Python code
2
3def minTimeDifference(timePoints):
4 def toMinutes(time):
5 h, m = map(int, time.split(':'))
6 return h * 60 + m
7
8 minutes = sorted(toMinutes(tp) for tp in timePoints)
9 min_diff = float('inf')
10 for i in range(1, len(minutes)):
11 min_diff = min(min_diff, minutes[i] - minutes[i - 1])
12 # Check wrap-around difference
13 min_diff = min(min_diff, 1440 - (minutes[-1] - minutes[0]))
14 return min_diffℹ
Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(n) because we store the converted minutes in an array.
- 1Sorting helps in reducing the number of comparisons needed to find the minimum difference.
- 2The wrap-around case is crucial when dealing with circular time formats.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.