MediumNo. 0539

Minimum Time Difference — LeetCode 539 Python Solution

Pattern
Sorting
Topics
Array, Math, String, Sorting
Reading time
2 min

The problem

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

Input
timePoints = ["23:59","00:00"]
Output
1

Python solution

PythonSolution
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))

Complexity

Time
O(n log n)
Space · auxiliary
O(n)where n is the number of time points

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 539. Minimum Time Difference is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 539. Minimum Time Difference?

LeetCode 539. Minimum Time Difference is rated Medium on LeetCode.

What is the time complexity of LeetCode 539. Minimum Time Difference?

The Python solution on this page runs in O(n log n).

What is the space complexity of LeetCode 539. Minimum Time Difference?

The Python solution on this page uses O(n), where n is the number of time points auxiliary space.

What topics does LeetCode 539. Minimum Time Difference cover?

LeetCode 539. Minimum Time Difference is tagged Array, Math, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.