Python 0539.py
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
n = []
for i in timePoints:
parts = i.split(":")
minutes = int(parts[0]) * 60 + int(parts[1])
n.append(minutes)
if (minutes < 12*60):
n.append(minutes + 24*60)
n.sort()
result = n[1] - n[0]
for i in range(1, len(n)):
result = min(result, n[i] - n[i -1])
return result
Difficulty
and has an acceptance rate of about 63% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
- Sorting
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of finding the smallest difference, in minutes, between any two timestamps given in "HH:MM" 24-hour format. It works by converting each timestamp into an integer count of minutes since midnight, extending the set of values to simplify the circular nature of a 24-hour clock, sorting the resulting list, and then scanning the sorted list to locate the minimal adjacent gap.
Conversion of Input Strings
The first logical block iterates over the input list, splits each string at the colon, and computes the total minutes.
n = []
for i in timePoints:
parts = i.split(":")
minutes = int(parts[0]) * 60 + int(parts[1])
n.append(minutes)
By turning "HH:MM" into a single integer, arithmetic comparisons become straightforward and avoid string handling overhead.
Handling the Circular Clock
A 24-hour clock wraps around at midnight, so the distance between "23:55" and "00:10" is 15 minutes, not the raw difference of 1,425 minutes. The code addresses this by duplicating every time that occurs before noon and adding a full-day offset (24 × 60 minutes).
if (minutes < 12*60):
n.append(minutes + 24*60)
This duplication creates a linear representation where the wrap-around gap appears as a regular adjacent difference after sorting. Consequently, the algorithm can treat the problem as a simple linear scan without special case logic for midnight.
Sorting the Minute Values
All minute values, including the duplicated ones, are placed into a single list and sorted in ascending order.
n.sort()
Sorting arranges the times so that the smallest gap will always be found between consecutive elements, eliminating the need for a nested comparison of every pair.
Scanning for the Minimum Gap
After sorting, the algorithm initializes the result with the difference between the first two entries and then iterates through the list, updating the result whenever a smaller adjacent difference is encountered.
result = n[1] - n[0]
for i in range(1, len(n)):
result = min(result, n[i] - n[i -1])
Because the list now contains the original times plus their 24-hour shifted counterparts, the loop naturally evaluates both ordinary gaps and the midnight crossing gap.
Edge Cases Addressed
When two timestamps are identical, the conversion step produces duplicate minute values. The subsequent sorting places these duplicates next to each other, and the scan immediately yields a difference of zero, which is the correct minimal result.
Times that lie on opposite sides of midnight, such as "23:59" and "00:01", are handled by the duplication logic: the early-morning time receives a 24-hour offset, turning it into 1441 minutes, while the late-night time remains 1439. After sorting, the adjacent difference becomes 2 minutes, correctly reflecting the circular distance.
The condition minutes < 12*60 ensures that only times in the first half of the day are duplicated, which is sufficient because any minimal crossing gap must involve a time before noon paired with a time after noon when viewed on the extended line.
Performance Optimizations
The code performs a single pass to convert strings to integers, avoiding repeated parsing. By using integer arithmetic exclusively, it eliminates the overhead of datetime objects or external libraries.
Duplicating only the first-half-day timestamps reduces the size of the extended list compared to duplicating every entry, thereby keeping the sorting workload lower while still guaranteeing that the wrap-around gap is represented.
The final linear scan computes the minimum using a constant-time min operation per iteration, ensuring that the dominant cost remains the sort, which is efficiently handled by Python’s highly optimized Timsort algorithm.
Overall, the implementation leverages a compact transformation and a single sorted traversal to achieve an efficient solution for the minimum time difference problem.
ELI5 - Simplified Explanation
Imagine you have a list of times on a clock, like ten o'clock or two-thirty. Each of these times is written with a little colon in the middle. The computer takes each time and changes it into just the total number of minutes that have passed since the start of the day. To make everything easier to compare, it also adds extra minutes for the next day, which acts like having a second clock right behind the first one.
Once all those times are turned into simple piles of minutes, everything gets lined up from the smallest amount of minutes to the biggest amount. Think of it like putting blocks in a row from shortest to tallest. After the blocks are in order, the computer looks at the distance between each pair of neighbors. It keeps track of the smallest gap it finds between any two times. This gap shows the number of minutes between the two closest times on the clock.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | Swift | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | JS | ||||||||||
| everthis | JS | ||||||||||
| fpdjsns | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JS | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, Swift, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | JavaScript | ||||||||||
| everthis | JavaScript | ||||||||||
| fpdjsns | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 2162: Minimum Cost to Set Cooking Time
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality