Skip to content
Problem 539 · LeetCode 539(opens in a new tab)

Minimum Time Difference

MediumMath

You are given a list of times on a 24-hour clock, each written as "HH:MM". The clock wraps around: after 23:59 comes 00:00.

Return the smallest number of minutes between any two of the times in the list, measured whichever way round the clock is shorter.

Example 1

Input:  timePoints = ["21:40", "00:20", "23:05", "08:00"]
Output: 75
Why:    23:05 to 00:20 across midnight is 75 minutes
2 more examples and the constraints

Example 2

Input:  timePoints = ["13:15", "06:45", "13:15"]
Output: 0
Why:    13:15 appears twice

Example 3

Input:  timePoints = ["00:00", "12:00"]
Output: 720
Why:    exactly half a day either way round

Constraints

  • 2 ≤ length of timePoints ≤ 20,000
  • Every entry is a valid time "HH:MM", from 00:00 to 23:59
  • Times may repeat

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Compare every pairO(n²)
  2. Sort, then check neighboursO(n log n)
  3. Mark minutes in 1,440 slotsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 20,000 timesVerdict
Compare every pairO(n²)
Mention it, then move on
Sort, then check neighboursO(n log n)
Passes; easy to explain
Mark minutes in 1,440 slotsO(n)
Best; uses the small clock

n = number of times. The clock has 1,440 minutes.

Edge cases to test

  • Repeated time. Two equal times give 0, and nothing can beat that.
  • Across midnight. "23:59" and "00:00" are 1 minute apart, not 1,439.
  • Half a day. "00:00" and "12:00" are 720 apart either way.
  • More than 1,440 times. Some minute must repeat, so the answer is 0.

Common mistakes

  • Forgetting the wrap-around gap between the latest and the earliest time.
  • Sorting the strings and subtracting them as text instead of converting to minutes.
  • Using 1,439 or 24·60 − 1 as the length of the day instead of 1,440.

How to talk through it

  1. 1Clarify. Can times repeat? Is the distance measured the shorter way round the clock?
  2. 2Give the brute force. Compare every pair with min(d, 1440 − d); O(n²) is too slow for 20,000 times.
  3. 3Sort and look next door. In order, the closest pair is adjacent, except for the wrap from last to first.
  4. 4Use the small range. Only 1,440 minutes exist, so mark slots instead of sorting, and stop early on a repeat.
  5. 5Test out loud. Run a repeat, a midnight wrap, and two times exactly 12 hours apart.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?