Minimum Time Difference

Updated on 18 June, 2025
Minimum Time Difference header image

Problem Statement

In this task, you are given a list containing time points in 24-hour format represented as "HH:MM". You are required to determine and return the smallest minute difference between any two given time points in the list. Each time comparison should be precise and account for possible day wrap-arounds, ensuring the differences calculated consider the sequential nature of a 24-hour time cycle.

Examples

Example 1

Input:

timePoints = ["23:59","00:00"]

Output:

1

Explanation:

The difference between "23:59" and "00:00" is 1 minute due to the wrap-around at midnight.

Example 2

Input:

timePoints = ["00:00","23:59","00:00"]

Output:

0

Explanation:

Two of the same time points exist ("00:00"), so the minimum difference is 0 minutes.

Constraints

  • 2 <= timePoints.length <= 2 * 10^4
  • timePoints[i] is in the format "HH:MM"

Approach and Intuition

Understanding the Problem

The challenge lies in accurately calculating minute differences between all time points, accounting for the 24-hour cycle. The day wrap-around between "23:59" and "00:00" must be explicitly handled to avoid incorrect minimum values.

Step-by-Step Approach

  1. Convert Times to Minutes: Convert each "HH:MM" time string into its total minutes since midnight using: total_minutes = hours * 60 + minutes

  2. Sort the Time Points: Sorting all converted minute values puts them in chronological order, making it easier to calculate pairwise differences.

  3. Calculate Minute Differences: Iterate through the sorted list and compute the difference between each consecutive pair. Additionally, compute the difference between the last and the first time (circular wrap-around) as: 1440 - last + first

  4. Determine the Minimum Difference: Return the smallest difference found among all computed differences.

Performance Notes

  • The conversion of times is O(n), sorting is O(n log n), and scanning for minimum difference is O(n).
  • Since 24 hours = 1440 minutes, if the number of time points exceeds 1440, a duplicate must exist — this early check can be used to return 0 immediately.

This approach ensures correctness, efficiency, and proper handling of edge cases like duplicates and midnight wrap-arounds.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int minimumTimeDifference(vector<string>& timePoints) {
        vector<bool> timeInMinutes(1440, false); // 24 * 60 minutes in a day
        for (auto &t : timePoints) {
            int hour = stoi(t.substr(0, 2));
            int minute = stoi(t.substr(3));
            int totalMinutes = hour * 60 + minute;
            if (timeInMinutes[totalMinutes]) return 0; // already seen this time, min difference is zero
            timeInMinutes[totalMinutes] = true;
        }

        int minDifference = INT_MAX;
        int first = INT_MAX;
        int last = INT_MIN;
        int previous = -1;

        for (int i = 0; i < 1440; i++) {
            if (timeInMinutes[i]) {
                if (previous != -1) {
                    minDifference = min(minDifference, i - previous);
                }
                if (first == INT_MAX) first = i;
                last = i;
                previous = i;
            }
        }

        // Check difference between last and first in circular manner
        minDifference = min(minDifference, 1440 - last + first);
        return minDifference;
    }
};

The given C++ program calculates the minimum difference in minutes between any two given times in a list. Follow these steps to understand the approach taken to solve this:

  1. An array, timeInMinutes, is initialized to represent each minute of the day. Each index corresponds to a minute from 00:00 to 23:59, initialized to false.

  2. Each time string from the timePoints vector is converted into minutes using standard string manipulation and arithmetic. It keeps track of times seen by marking the corresponding index in the timeInMinutes array as true.

  3. If any time point occurs more than once, the function immediately returns zero as the smallest possible time difference.

  4. After populating the timeInMinutes array, a scan identifies the first and last time set in the array and calculates the minimum difference between consecutive true indices.

  5. Lastly, the function considers the circular nature of time (i.e., difference between a very late time and a very early time the next day). It calculates the difference between the last and first true index as if the day rolled over and checks if this "circular difference" is smaller.

With this approach, you ensure that all possible cases for time difference are covered efficiently, keeping the solution optimal in terms of time complexity.

java
class Solution {

    public int minimumTimeDifference(List<String> timePoints) {
        // boolean array to track minute presence
        boolean[] timeInMinutes = new boolean[1440]; // 24 * 60
        for (String time : timePoints) {
            int minutes = Integer.parseInt(time.substring(0, 2)) * 60 + Integer.parseInt(time.substring(3));
            if (timeInMinutes[minutes]) return 0;
            timeInMinutes[minutes] = true;
        }
        int previous = Integer.MAX_VALUE;
        int first = Integer.MAX_VALUE;
        int last = Integer.MAX_VALUE;
        int minimumDifference = Integer.MAX_VALUE;

        // loop to find the smallest difference
        for (int i = 0; i < timeInMinutes.length; i++) {
            if (timeInMinutes[i]) {
                if (previous != Integer.MAX_VALUE) {
                    minimumDifference = Math.min(minimumDifference, i - previous);
                }
                previous = i;
                if (first == Integer.MAX_VALUE) {
                    first = i;
                }
                last = i;
            }
        }

        // compute smallest between last and first considering circular day
        return Math.min(minimumDifference, 1440 - last + first);
    }
}

The Java code provided offers a solution to find the minimum time difference between any two given times in a list. This is typically useful in scenarios where you need to determine the shortest duration between times, which could be crucial for scheduling or optimization tasks.

Strategy Overview:

  • The solution leverages a boolean array timeInMinutes of size 1440 (to represent minutes in a day) to track if a minute is covered by the input times.
  • The time points are converted into minutes since midnight and marked in the timeInMinutes array.
  • If any time point is repeated (i.e., it converts to the same minute value), the function immediately returns 0, indicating no time difference.

Critical Steps:

  1. Iterate through each time string to convert it into the total minutes from the start of the day, and mark it in the timeInMinutes array. If a minute is already marked, it means you've found a duplicate time point, and the function returns 0.
  2. Initialize variables for tracking the first and last minute seen, and a variable for the previous minute as you iterate through the minutes of the day.
  3. Traverse the timeInMinutes array to compute the direct minimum difference between consecutive time points recorded.
  4. Additionally, compute the circular minimum difference taking into account the wrap-around from the last to the first time point in a day.
  5. The result is the smallest value found from the differences calculated.

Key Operations:

  • Using boolean arrays for efficient lookup and marking of the presence of minutes.
  • Mathematical operations for converting HH:MM time to minutes.
  • Logical checks and minimum calculations to determine the smallest time difference.

The approach is efficient with a linear runtime in relation to the number of minutes in a day, which is constant, therefore making the solution scalable to any number of input time points within the 24-hour bounds.

python
class Solution:
    def minimumTimeDifference(self, timeList: List[str]) -> int:
        # Array to keep track of all minutes occurrences 
        timeInMinutes = [False] * (24 * 60)
        for time in timeList:
            hrs, mins = map(int, time.split(":"))
            totalMinutes = hrs * 60 + mins
            if timeInMinutes[totalMinutes]:
                return 0  # Found duplicate times
            timeInMinutes[totalMinutes] = True
            
        previousMinute = float("inf")
        initialMinute = float("inf")
        finalMinute = float("inf")
        minimumDifference = float("inf")

        # Loop to calculate the minimum difference between times
        for minute in range(24 * 60):
            if timeInMinutes[minute]:
                if previousMinute != float("inf"):
                    minimumDifference = min(minimumDifference, minute - previousMinute)
                previousMinute = minute
                if initialMinute == float("inf"):
                    initialMinute = minute
                finalMinute = minute

        # wrap around the clock comparison
        return min(minimumDifference, 24 * 60 - finalMinute + initialMinute)

This solution presents a method to find the minimum difference in minutes between any two given times in a list using Python. Focus on converting each time into minutes past midnight and then using an array to track all existing time points for efficient difference calculation. Follow these detailed steps:

  1. Convert all time points into total minutes from midnight and store them in a Boolean array named timeInMinutes, sized to accommodate all minutes in a day (1440, representing 24 hours * 60 minutes).

  2. If at any point a time repeats (i.e., if the Boolean value in the array for that time is True), return 0 immediately because the minimum time difference cannot be less than zero.

  3. Initialize variables to hold previously encountered time in minutes (previousMinute), the first time in minutes encountered (initialMinute), the last time in minutes encountered (finalMinute), and the minimum time difference found (minimumDifference). All are initially set to infinity, appropriate for comparison purposes.

  4. Loop through each minute of the day using a range from 0 to 1439 (24*60). For each minute recorded in timeInMinutes, update previousMinute, initialMinute, and finalMinute. Calculate the difference between consecutive times and update minimumDifference accordingly.

  5. To handle the cyclical nature of time (e.g., comparing times around midnight), also consider the difference that includes the day wrap-around by calculating the time difference between the last and first times recorded and seeing if it offers a smaller difference.

  6. Finally, return minimumDifference which will have the smallest time difference found, including considering the wrap-around time effect.

Through this solution, handle both the typical differences and the edge cases such as minimum differences spanning days, efficiently managing time complexities by avoiding direct comparisons of every pair of times.

Comments

No comments yet.