KatInterview

539. Minimum Time Difference

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum time difference in minutes between any two given time points in "HH:MM" format. The key challenge lies in efficiently handling the time comparisons and the circular nature of a 24-hour clock. For instance, the difference between "23:59" and "00:00" is just 1 minute, not 23 hours and 59 minutes.

Solution

Minimum Time Difference in Python

class Solution:
    def findMinDifference(self, timePoints: List[str]) -> int:
        # There are 24 * 60 = 1440 minutes in a day.
        # If there are more than 1440 time points, by pigeonhole principle,
        # at least two time points must be the same. So the difference is 0.
        if len(timePoints) > 1440:
            return 0

        # Use a boolean list to mark the minutes that appear in the input.
        seen = [False] * 1440
        for time in timePoints:
            # Parse HH:MM format.
            hours = int(time[:2])
            minutes = int(time[3:])
            total_minutes = hours * 60 + minutes

            # If we have seen this time before, the difference is 0.
            if seen[total_minutes]:
                return 0
            seen[total_minutes] = True
        
        min_diff = float('inf')
        first_minute = -1
        prev_minute = -1

        # Iterate through all 1440 minutes to find the minimum difference
        # between consecutive seen time points.
        for i in range(1440):
            if seen[i]:
                if first_minute == -1:
                    # This is the first time point we've seen.
                    first_minute = i
                if prev_minute != -1:
                    # Calculate difference with the previous time point.
                    min_diff = min(min_diff, i - prev_minute)
                prev_minute = i

        # Handle the wrap-around case (e.g., 23:59 and 00:01).
        # The difference is between the first and the last time point.
        wrap_around_diff = (first_minute + 1440) - prev_minute
        min_diff = min(min_diff, wrap_around_diff)
        
        return min_diff

Minimum Time Difference in Java

class Solution {
    public int findMinDifference(List<String> timePoints) {
        // There are 24 * 60 = 1440 minutes in a day.
        // If there are more than 1440 time points, by pigeonhole principle,
        // at least two time points must be the same. So the difference is 0.
        if (timePoints.size() > 1440) {
            return 0;
        }

        // Use a boolean array to mark the minutes that appear in the input.
        boolean[] seen = new boolean[1440];
        for (String time : timePoints) {
            // Parse HH:MM format.
            int hours = Integer.parseInt(time.substring(0, 2));
            int minutes = Integer.parseInt(time.substring(3, 5));
            int totalMinutes = hours * 60 + minutes;

            // If we have seen this time before, the difference is 0.
            if (seen[totalMinutes]) {
                return 0;
            }
            seen[totalMinutes] = true;
        }

        int minDiff = Integer.MAX_VALUE;
        int firstMinute = -1;
        int prevMinute = -1;

        // Iterate through all 1440 minutes to find the minimum difference
        // between consecutive seen time points.
        for (int i = 0; i < 1440; i++) {
            if (seen[i]) {
                if (firstMinute == -1) {
                    // This is the first time point we've seen.
                    firstMinute = i;
                }
                if (prevMinute != -1) {
                    // Calculate difference with the previous time point.
                    minDiff = Math.min(minDiff, i - prevMinute);
                }
                prevMinute = i;
            }
        }

        // Handle the wrap-around case (e.g., 23:59 and 00:01).
        // The difference is between the first and the last time point.
        int wrapAroundDiff = (firstMinute + 1440) - prevMinute;
        minDiff = Math.min(minDiff, wrapAroundDiff);

        return minDiff;
    }
}

Minimum Time Difference in C++

class Solution {
public:
    int findMinDifference(vector<string>& timePoints) {
        // There are 24 * 60 = 1440 minutes in a day.
        // If there are more than 1440 time points, by pigeonhole principle,
        // at least two time points must be the same. So the difference is 0.
        if (timePoints.size() > 1440) {
            return 0;
        }

        // Use a boolean array to mark the minutes that appear in the input.
        vector<bool> seen(1440, false);
        for (const string& time : timePoints) {
            // Parse HH:MM format.
            int hours = stoi(time.substr(0, 2));
            int minutes = stoi(time.substr(3, 2));
            int totalMinutes = hours * 60 + minutes;

            // If we have seen this time before, the difference is 0.
            if (seen[totalMinutes]) {
                return 0;
            }
            seen[totalMinutes] = true;
        }

        int minDiff = INT_MAX;
        int firstMinute = -1;
        int prevMinute = -1;

        // Iterate through all 1440 minutes to find the minimum difference
        // between consecutive seen time points.
        for (int i = 0; i < 1440; ++i) {
            if (seen[i]) {
                if (firstMinute == -1) {
                    // This is the first time point we've seen.
                    firstMinute = i;
                }
                if (prevMinute != -1) {
                    // Calculate difference with the previous time point.
                    minDiff = min(minDiff, i - prevMinute);
                }
                prevMinute = i;
            }
        }

        // Handle the wrap-around case (e.g., 23:59 and 00:01).
        // The difference is between the first and the last time point.
        int wrapAroundDiff = (firstMinute + 1440) - prevMinute;
        minDiff = min(minDiff, wrapAroundDiff);

        return minDiff;
    }
};

Minimum Time Difference in TypeScript

function findMinDifference(timePoints: string[]): number {
    // There are 24 * 60 = 1440 minutes in a day.
    // If there are more than 1440 time points, by pigeonhole principle,
    // at least two time points must be the same. So the difference is 0.
    if (timePoints.length > 1440) {
        return 0;
    }

    // Use a boolean array to mark the minutes that appear in the input.
    const seen = new Array(1440).fill(false);
    for (const time of timePoints) {
        // Parse HH:MM format.
        const hours = parseInt(time.substring(0, 2));
        const minutes = parseInt(time.substring(3, 5));
        const totalMinutes = hours * 60 + minutes;

        // If we have seen this time before, the difference is 0.
        if (seen[totalMinutes]) {
            return 0;
        }
        seen[totalMinutes] = true;
    }

    let minDiff = Number.MAX_SAFE_INTEGER;
    let firstMinute = -1;
    let prevMinute = -1;

    // Iterate through all 1440 minutes to find the minimum difference
    // between consecutive seen time points.
    for (let i = 0; i < 1440; i++) {
        if (seen[i]) {
            if (firstMinute === -1) {
                // This is the first time point we've seen.
                firstMinute = i;
            }
            if (prevMinute !== -1) {
                // Calculate difference with the previous time point.
                minDiff = Math.min(minDiff, i - prevMinute);
            }
            prevMinute = i;
        }
    }

    // Handle the wrap-around case (e.g., 23:59 and 00:01).
    // The difference is between the first and the last time point.
    const wrapAroundDiff = (firstMinute + 1440) - prevMinute;
    minDiff = Math.min(minDiff, wrapAroundDiff);

    return minDiff;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.