Problem 539

Abstract / Summary

Given a list of times in 24 hour format find the smallest difference in minutes between any two times.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
17 lines | 491 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 63% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Sorting
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.74 | σ = 1.58

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
36 links | 21 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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