Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Time Difference solution and explanation

MediumArrayMathSortingString5 min read62.7% acceptanceUpdated 9 Apr 2026
LeetCode 539. Minimum Time Difference (Solution Explained)Nick White · 15:01 · 13K viewsWatch on YouTube
9 more videos on this problem
  1. LeetCode 539. Minimum Time Difference (Solution Explained)Nick White · 15:01 · 13K views
  2. Minimum Time Difference - Leetcode 539 - PythonNeetCodeIO · 21:43 · 11K views
  3. Minimum Time Difference | Easy Approach | Detailed | Leetcode 539 | codestorywithMIKcodestorywithMIK · 24:01 · 9K views
  4. MINIMUM TIME DIFFERENCE | PYTHON | LEETCODE # 539Cracking FAANG · 8:45 · 4K views
  5. ✅Minimum Time Difference - LeetCode 539 - Total Minutes in 1 Day - Explained in DetailLeet Logics · 7:09 · 1K views
  6. [Java] Leetcode 539. Minimum Time Difference [Array #6]Eric Programming · 9:03 · 1K views
  7. leetcode 539. Minimum Time Differencealgorithm everyday · 17:07 · 546 views
  8. 539. Minimum Time Difference (Leetcode Medium)Programming Live with Larry · 5:24 · 264 views
  9. Leetcode 539: Minimum Time DifferenceYouScaredMe · 4:53 · 165 views
  10. LeetCode 539 - Minimum Time Difference - JavaAlpha-Code · 12:49 · 148 views

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 1:

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

Example 2:

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

Constraints:

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

Approach overview

Problem Overview: You receive a list of time points in HH:MM format. The task is to compute the smallest difference in minutes between any two time points. Because time wraps around midnight (e.g., 23:59 and 00:00), the comparison must also consider the circular nature of a 24‑hour clock.

Approach 1: Sorting and Finding Minimum Difference (O(n log n) time, O(n) space)

Convert each time string into total minutes from midnight (hour * 60 + minute). Store these values in an array and sort them. Once sorted, iterate through adjacent elements and compute the difference between each pair to track the minimum gap. The circular edge case is handled by comparing the last time of the day with the first time plus 1440 minutes. Sorting simplifies the comparison logic because the closest times must appear next to each other in the ordered list.

This method relies on basic operations from array processing and sorting. It works well for general input sizes and is easy to implement in most languages. Time complexity comes from sorting (O(n log n)), while the scan for differences runs in O(n). Space complexity is O(n) due to the converted minute array.

Approach 2: Using a Boolean Array to Track Minutes (O(n) time, O(1) space)

A day contains exactly 1440 minutes. Instead of sorting, allocate a boolean array of size 1440 and mark each minute that appears in the input. Convert every time string to its minute index and check if that index is already marked. If it is, the minimum difference is immediately 0 because duplicate times exist.

After marking all time points, scan the boolean array to locate consecutive marked minutes and compute their differences. Track the first and last seen minutes to correctly compute the circular difference across midnight. Because the array size is fixed (1440), the scan runs in constant time relative to the input size.

This technique uses ideas from array indexing and simple math transformations. The algorithm runs in O(n) time for inserting time points and O(1440) for scanning, which simplifies to O(n). Space complexity is effectively O(1) since the 1440‑length array is constant regardless of input size.

Recommended for interviews: The sorting approach is the most commonly expected solution because it is straightforward and demonstrates clean reasoning about ordering and edge cases like the midnight wrap‑around. Mentioning the boolean‑array optimization shows deeper insight: you recognize the bounded domain of minutes in a day and reduce the complexity to linear time. Showing both approaches signals strong problem‑solving depth in interviews.

Approach 1: Sorting and Finding Minimum Difference

Convert the time into minutes from "00:00", sort, then find the smallest difference between any two adjacent times while also considering the difference across midnight.

def time_to_minutes(time):
    hours, minutes = map(int, time.split(':'))
    return hours * 60 + minutes

def find_min_difference(time_points):
    minutes = [time_to_minutes(time) for time in time_points]
    minutes.sort()
    min_diff = float('inf')
    for i in range(1, len(minutes)):
        min_diff = min(min_diff, minutes[i] - minutes[i - 1])
    wrap_around_diff = minutes[0] + 1440 - minutes[-1]
    min_diff = min(min_diff, wrap_around_diff)
    return min_diff

# Example usage
time_points = ["23:59", "00:00"]
print(find_min_difference(time_points))
import java.util.*;

public class MinimumTimeDifference {
    private static int timeToMinutes(String time) {
        int hours = Integer.parseInt(time.substring(0, 2));
        int minutes = Integer.parseInt(time.substring(3, 5));
        return hours * 60 + minutes;
    }

    public static int findMinDifference(List<String> timePoints) {
        List<Integer> minutes = new ArrayList<>();
        for (String time : timePoints) {
            minutes.add(timeToMinutes(time));
        }

        Collections.sort(minutes);

        int minDiff = Integer.MAX_VALUE;
        for (int i = 1; i < minutes.size(); ++i) {
            minDiff = Math.min(minDiff, minutes.get(i) - minutes.get(i - 1));
        }

        int wrapAroundDiff = minutes.get(0) + 1440 - minutes.get(minutes.size() - 1);
        minDiff = Math.min(minDiff, wrapAroundDiff);

        return minDiff;
    }

    public static void main(String[] args) {
        List<String> timePoints = Arrays.asList("23:59", "00:00");
        System.out.println(findMinDifference(timePoints));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;

int timeToMinutes(const string& time) {
    int hours = stoi(time.substr(0, 2));
    int minutes = stoi(time.substr(3, 2));
    return hours * 60 + minutes;
}

int findMinDifference(vector<string>& timePoints) {
    vector<int> minutes;
    for (const auto& time : timePoints) {
        minutes.push_back(timeToMinutes(time));
    }

    sort(minutes.begin(), minutes.end());

    int minDiff = INT_MAX;
    for (int i = 1; i < minutes.size(); ++i) {
        minDiff = min(minDiff, minutes[i] - minutes[i - 1]);
    }

    int wrapAroundDiff = minutes[0] + 1440 - minutes.back();
    minDiff = min(minDiff, wrapAroundDiff);

    return minDiff;
}

int main() {
    vector<string> timePoints = {"23:59", "00:00"};
    cout << findMinDifference(timePoints) << endl;
    return 0;
}
function timeToMinutes(time) {
    const [hours, minutes] = time.split(':').map(Number);
    return hours * 60 + minutes;
}

function findMinDifference(timePoints) {
    const minutes = timePoints.map(timeToMinutes);
    minutes.sort((a, b) => a - b);

    let minDiff = Infinity;
    for (let i = 1; i < minutes.length; i++) {
        minDiff = Math.min(minDiff, minutes[i] - minutes[i - 1]);
    }

    const wrapAroundDiff = minutes[0] + 1440 - minutes[minutes.length - 1];
    minDiff = Math.min(minDiff, wrapAroundDiff);

    return minDiff;
}

// Example usage:
const timePoints = ["23:59", "00:00"];
console.log(findMinDifference(timePoints));
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int timeToMinutes(const char* time) {
    int hours = (time[0] - '0') * 10 + (time[1] - '0');
    int minutes = (time[3] - '0') * 10 + (time[4] - '0');
    return hours * 60 + minutes;
}

int compare(const void* a, const void* b) {
    return *((int*)a) - *((int*)b);
}

int findMinDifference(char** timePoints, int timePointsSize) {
    int* minutes = (int*)malloc(sizeof(int) * timePointsSize);
    for (int i = 0; i < timePointsSize; ++i)
        minutes[i] = timeToMinutes(timePoints[i]);

    qsort(minutes, timePointsSize, sizeof(int), compare);

    int minDiff = INT_MAX;
    for (int i = 1; i < timePointsSize; ++i) {
        int diff = minutes[i] - minutes[i - 1];
        if (diff < minDiff) minDiff = diff;
    }

    int wrapAroundDiff = minutes[0] + 1440 - minutes[timePointsSize - 1];
    if (wrapAroundDiff < minDiff) minDiff = wrapAroundDiff;

    free(minutes);
    return minDiff;
}

int main() {
    char* timePoints[] = {"23:59", "00:00"};
    int size = 2;
    printf("%d\n", findMinDifference(timePoints, size));
    return 0;
}
using System;
using System.Collections.Generic;

public class MinimumTimeDifference {
    private static int TimeToMinutes(string time) {
        int hours = int.Parse(time.Substring(0, 2));
        int minutes = int.Parse(time.Substring(3, 2));
        return hours * 60 + minutes;
    }

    public static int FindMinDifference(IList<string> timePoints) {
        List<int> minutes = new List<int>();
        foreach (var time in timePoints) {
            minutes.Add(TimeToMinutes(time));
        }

        minutes.Sort();

        int minDiff = int.MaxValue;
        for (int i = 1; i < minutes.Count; ++i) {
            minDiff = Math.Min(minDiff, minutes[i] - minutes[i - 1]);
        }

        int wrapAroundDiff = minutes[0] + 1440 - minutes[minutes.Count - 1];
        minDiff = Math.Min(minDiff, wrapAroundDiff);

        return minDiff;
    }

    public static void Main() {
        List<string> timePoints = new List<string> { "23:59", "00:00" };
        Console.WriteLine(FindMinDifference(timePoints));
    }
}

This Python function converts each time point to minutes, sorts them, and determines the smallest difference between consecutive times. It also handles differences across midnight.

Complexity

Time Complexity: O(n log n).
Space Complexity: O(n).

Try this approach in the editor

Approach 2: Using a Boolean Array to Track Minutes

Mark each minute of the day in a boolean array once any time point corresponds to it. Then traverse the array to find the smallest gap between marked minutes, considering wrap-around. This is efficient because it eliminates the need for sorting.

def time_to_minutes(time):
    hours, minutes = map(int, time.split(':'))
    return hours * 60 + minutes

def find_min_difference(time_points):
    minutes = [False] * 1440
    for time in time_points:
        minute = time_to_minutes(time)
        if minutes[minute]:
            return 0
        minutes[minute] = True

    first = last = prev = -1
    min_diff = float('inf')
    for i in range(1440):
        if minutes[i]:
            if first == -1:
                first = i
            if prev != -1:
                min_diff = min(min_diff, i - prev)
            prev = i
            last = i
    min_diff = min(min_diff, first + 1440 - last)
    return min_diff

# Example usage
time_points = ["23:59", "00:00"]
print(find_min_difference(time_points))
import java.util.*;

public class MinimumTimeDifference {
    private static int timeToMinutes(String time) {
        int hours = Integer.parseInt(time.substring(0, 2));
        int minutes = Integer.parseInt(time.substring(3, 5));
        return hours * 60 + minutes;
    }

    public static int findMinDifference(List<String> timePoints) {
        boolean[] minutes = new boolean[1440];
        for (String time : timePoints) {
            int minute = timeToMinutes(time);
            if (minutes[minute]) return 0;
            minutes[minute] = true;
        }

        int first = -1, last = -1, prev = -1, minDiff = 1440;
        for (int i = 0; i < 1440; i++) {
            if (minutes[i]) {
                if (first == -1) first = i;
                if (prev != -1) minDiff = Math.min(minDiff, i - prev);
                prev = i;
                last = i;
            }
        }
        minDiff = Math.min(minDiff, first + 1440 - last);

        return minDiff;
    }

    public static void main(String[] args) {
        List<String> timePoints = Arrays.asList("23:59", "00:00");
        System.out.println(findMinDifference(timePoints));
    }
}
#include <iostream>
#include <vector>
#include <string>
#include <climits>

using namespace std;

int timeToMinutes(const string& time) {
    int hours = stoi(time.substr(0, 2));
    int minutes = stoi(time.substr(3, 2));
    return hours * 60 + minutes;
}

int findMinDifference(vector<string>& timePoints) {
    vector<bool> minutes(1440, false);
    for (const auto& time : timePoints) {
        int minute = timeToMinutes(time);
        if (minutes[minute]) return 0;
        minutes[minute] = true;
    }

    int first = -1, last = -1, prev = -1, minDiff = INT_MAX;
    for (int i = 0; i < 1440; ++i) {
        if (minutes[i]) {
            if (first == -1) first = i;
            if (prev != -1) minDiff = min(minDiff, i - prev);
            prev = i;
            last = i;
        }
    }
    minDiff = min(minDiff, first + 1440 - last);
    return minDiff;
}

int main() {
    vector<string> timePoints = {"23:59", "00:00"};
    cout << findMinDifference(timePoints) << endl;
    return 0;
}
function timeToMinutes(time) {
    const [hours, minutes] = time.split(':').map(Number);
    return hours * 60 + minutes;
}

function findMinDifference(timePoints) {
    const minutes = new Array(1440).fill(false);

    for (const time of timePoints) {
        const minute = timeToMinutes(time);
        if (minutes[minute]) return 0;
        minutes[minute] = true;
    }

    let first = -1, last = -1, prev = -1, minDiff = Infinity;
    for (let i = 0; i < 1440; i++) {
        if (minutes[i]) {
            if (first === -1) first = i;
            if (prev !== -1) minDiff = Math.min(minDiff, i - prev);
            prev = i;
            last = i;
        }
    }
    minDiff = Math.min(minDiff, first + 1440 - last);

    return minDiff;
}

// Example usage:
const timePoints = ["23:59", "00:00"];
console.log(findMinDifference(timePoints));
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int timeToMinutes(const char* time) {
    int hours = (time[0] - '0') * 10 + (time[1] - '0');
    int minutes = (time[3] - '0') * 10 + (time[4] - '0');
    return hours * 60 + minutes;
}

int findMinDifference(char** timePoints, int timePointsSize) {
    bool minutes[1440] = {false};
    for (int i = 0; i < timePointsSize; ++i) {
        int minute = timeToMinutes(timePoints[i]);
        if (minutes[minute]) return 0;
        minutes[minute] = true;
    }

    int first = -1, last = -1, prev = -1, minDiff = 1440;
    for (int i = 0; i < 1440; ++i) {
        if (minutes[i]) {
            if (first == -1) first = i;
            if (prev != -1) minDiff = (i - prev < minDiff) ? i - prev : minDiff;
            prev = i;
            last = i;
        }
    }
    minDiff = ((first + 1440 - last) < minDiff) ? (first + 1440 - last) : minDiff;
    return minDiff;
}

int main() {
    char* timePoints[] = {"23:59", "00:00"};
    int size = 2;
    printf("%d\n", findMinDifference(timePoints, size));
    return 0;
}
using System;
using System.Collections.Generic;

public class MinimumTimeDifference {
    private static int TimeToMinutes(string time) {
        int hours = int.Parse(time.Substring(0, 2));
        int minutes = int.Parse(time.Substring(3, 2));
        return hours * 60 + minutes;
    }

    public static int FindMinDifference(IList<string> timePoints) {
        bool[] minutes = new bool[1440];
        foreach (var time in timePoints) {
            int minute = TimeToMinutes(time);
            if (minutes[minute]) return 0;
            minutes[minute] = true;
        }

        int first = -1, last = -1, prev = -1, minDiff = 1440;
        for (int i = 0; i < 1440; ++i) {
            if (minutes[i]) {
                if (first == -1) first = i;
                if (prev != -1) minDiff = Math.Min(minDiff, i - prev);
                prev = i;
                last = i;
            }
        }
        minDiff = Math.Min(minDiff, first + 1440 - last);

        return minDiff;
    }

    public static void Main() {
        List<string> timePoints = new List<string> { "23:59", "00:00" };
        Console.WriteLine(FindMinDifference(timePoints));
    }
}

Python's approach uses a boolean list to mark all minutes accounted for. The smallest gap between true values is determined, considering the span across midnight separately.

Complexity

Time Complexity: O(n + M), M = 1440.
Space Complexity: O(M).

Try this approach in the editor

Approach 3: Sorting

We notice that there can be at most 24 times 60 = 1440 distinct time points. Therefore, if the length of timePoints exceeds 1440, it implies there are duplicate time points, and we can return 0 early.

Next, we iterate through the list of time points and convert it into a list of minutes nums. For example, for the time point 13:14, we convert it into 13 times 60 + 14.

Then, we sort the list of minutes in ascending order and append the smallest time nums[0] plus 1440 to the end of the list. This step is to handle the special case of the difference between the maximum and minimum values.

Finally, we iterate through the list of minutes to find the minimum difference between any two adjacent times.

The time complexity is O(n log n), and the space complexity is O(n), where n is the number of time points.

function findMinDifference(timePoints: string[]): number {
    if (timePoints.length > 1440) {
        return 0;
    }
    const n = timePoints.length;
    const nums: number[] = Array(n + 1);
    for (let i = 0; i < n; ++i) {
        const [hours, minutes] = timePoints[i].split(':').map(Number);
        nums[i] = hours * 60 + minutes;
    }
    nums.sort((a, b) => a - b);
    nums[n] = nums[0] + 1440;
    let ans = 1 << 30;
    for (let i = 1; i <= n; ++i) {
        ans = Math.min(ans, nums[i] - nums[i - 1]);
    }
    return ans;
}
func findMinDifference(timePoints []string) int {
	if len(timePoints) > 1440 {
		return 0
	}

	n := len(timePoints)
	nums := make([]int, n+1)
	for i, time := range timePoints {
		parts := strings.Split(time, ":")
		hours, _ := strconv.Atoi(parts[0])
		minutes, _ := strconv.Atoi(parts[1])
		nums[i] = hours*60 + minutes
	}

	sort.Ints(nums[:n])
	nums[n] = nums[0] + 1440

	ans := 1 << 30
	for i := 1; i <= n; i++ {
		ans = min(ans, nums[i]-nums[i-1])
	}

	return ans
}
class Solution {
    func findMinDifference(_ timePoints: [String]) -> Int {
        if timePoints.count > 1440 {
            return 0
        }

        var nums = [Int]()

        for t in timePoints {
            let time = t.split(separator: ":").map { Int($0)! }
            nums.append(time[0] * 60 + time[1])
        }

        nums.sort()
        nums.append(nums[0] + 1440)

        var ans = Int.max
        for i in 1..<nums.count {
            ans = min(ans, nums[i] - nums[i - 1])
        }

        return ans
    }
}
impl Solution {
    pub fn find_min_difference(time_points: Vec<String>) -> i32 {
        if time_points.len() > 1440 {
            return 0;
        }

        let n = time_points.len();
        let mut nums: Vec<i32> = Vec::with_capacity(n + 1);

        for time in time_points.iter() {
            let parts: Vec<i32> = time.split(':').map(|s| s.parse().unwrap()).collect();
            let minutes = parts[0] * 60 + parts[1];
            nums.push(minutes);
        }

        nums.sort();
        nums.push(nums[0] + 1440);

        let mut ans = i32::MAX;
        for i in 1..=n {
            ans = ans.min(nums[i] - nums[i - 1]);
        }

        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Sorting and Finding Minimum Difference

Time Complexity: O(n log n).
Space Complexity: O(n).

Using a Boolean Array to Track Minutes

Time Complexity: O(n + M), M = 1440.
Space Complexity: O(M).

Sorting–

Complexity analysis

ApproachTimeSpaceWhen to Use
Sorting and Finding Minimum DifferenceO(n log n)O(n)General solution that is simple to implement and commonly expected in interviews
Boolean Array for 1440 MinutesO(n)O(1)When exploiting the fixed 24‑hour domain for a faster linear-time solution

Frequently asked questions

Is Minimum Time Difference easy or hard?

Minimum Time Difference is typically categorized as a Medium problem. The challenge comes from handling the circular 24‑hour clock and recognizing that the smallest difference may occur across midnight.

Minimum Time Difference Python/Java solution

In Python or Java, convert each time string using split(':') and compute total minutes as hour * 60 + minute. Either store these values in a list and sort them, or mark them in a 1440‑length boolean array for a linear‑time solution.

How to solve Minimum Time Difference in O(n)?

Use a boolean array of size 1440 representing every minute in a day. Convert each time string to its minute index and mark it in the array. Then scan the array to find the smallest gap between marked minutes and handle the wrap‑around difference between the last and first times.

What is the best approach for Minimum Time Difference?

The most common solution sorts all time points after converting them to minutes. Once sorted, compare adjacent times and also check the circular difference between the last and first values. This approach runs in O(n log n) time and is widely expected in coding interviews.

Is Minimum Time Difference asked at Google/Amazon/Meta?

Minimum Time Difference is a classic time‑conversion and sorting problem that appears in interview preparation sets for companies like Amazon and Google. It tests understanding of string parsing, array processing, and edge cases involving circular time ranges.

What data structure is used in Minimum Time Difference?

Common implementations use arrays to store minute values after converting the HH:MM strings. The optimized approach uses a boolean array of size 1440 to track whether a particular minute appears, avoiding the need for sorting.

What is the time complexity of Minimum Time Difference?

The standard sorting solution runs in O(n log n) time because the time points must be ordered before comparing neighbors. A more optimized method uses a fixed boolean array of 1440 minutes and runs in O(n) time with constant space.

Comments

Now write it yourselfClose this page and solve Minimum Time Difference in the editor, without looking.
Practise Minimum Time Difference