Minimize Difference

Last Updated : 24 Jul, 2025

Given an array arr[] of strings, where each string represents a time in 24-hour format ("HH:MM:SS"), find the minimum absolute difference in seconds between any two time values.

Note: The clock wraps around at midnight, so the time difference between "23:59:59" and "00:00:00" is 1 second.

Examples:

Input: arr[] = ["12:30:15", "12:30:45"]
Output: 30
Explanation: The minimum time difference is 30 seconds, which is the difference between 12:30:15 and 12:30:45 just a 30-second gap between the two times.

Input: arr[] = ["00:00:01", "23:59:59", "00:00:05"]
Output: 2
Explanation: The time difference is minimum between "00:00:01" and "23:59:59" is minimum.

Try It Yourself
redirect icon

[Naive Approach] Sorting-Based - O(n log(n)) Time and O(n) Space

The naive solution converts all times into seconds, sorts them, and then computes the minimum difference between adjacent elements, including wrap-around between the last and first to handle midnight properly.

C++
#include <iostream>     
#include <vector>       
#include <string>       
#include <algorithm> 
#include <climits>      

using namespace std;

// Convert time string "HH:MM:SS" to total
// seconds since midnight
int toSeconds(string &time) {
    
    int h = stoi(time.substr(0, 2));   
    int m = stoi(time.substr(3, 2));   
    int s = stoi(time.substr(6, 2)); 
    
    return h * 3600 + m * 60 + s;      
}

// Compute the minimum difference in
// seconds between any two times
int minDifference(vector<string> arr) {
    vector<int> sec;
    int n = arr.size();

    // Convert all time strings to seconds
    for (int i = 0; i < n; i++) {
        sec.push_back(toSeconds(arr[i]));
    }

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

    int minDiff = INT_MAX;

    // Compare adjacent elements to find 
    // the smallest difference
    for (int i = 1; i < n; i++) {
        int diff = sec[i] - sec[i - 1];
        minDiff = min(diff, minDiff);
    }

    // Handle circular difference between
    // last and first time
    int wrapdiff = 86400 - sec[n - 1] + sec[0]; 
    minDiff = min(minDiff, wrapdiff);

    return minDiff;
}

int main(){
    vector<string> arr = {"12:30:15", "12:30:45"};
    
    cout << minDifference(arr) << endl;

    return 0;
}
Java
import java.util.*;

class GfG {
    
    // Convert "HH:MM:SS" to total seconds
    private static int toSeconds(String time) {
        
        int h = Integer.parseInt(time.substring(0, 2));
        int m = Integer.parseInt(time.substring(3, 5));
        int s = Integer.parseInt(time.substring(6, 8));
        
        return h * 3600 + m * 60 + s;
    }

    // Find the minimum time difference in seconds
    public static int minDifference(String[] arr) {
        
        int n = arr.length;
        int[] seconds = new int[n];

        // Convert all time strings 
        // to seconds
        for (int i = 0; i < n; i++) {
            seconds[i] = toSeconds(arr[i]);
        }

        Arrays.sort(seconds);

        int minDiff = Integer.MAX_VALUE;

        // Compare adjacent elements
        for (int i = 1; i < n; i++) {
            int diff = seconds[i] - seconds[i - 1];
            minDiff = Math.min(minDiff, diff);
        }

        // Handle circular wrap-around 
        // last and first
        int wrapDiff = 86400 - seconds[n - 1] + seconds[0];
        minDiff = Math.min(minDiff, wrapDiff);

        return minDiff;
    }

    public static void main(String[] args) {
        String[] arr = {"12:30:15", "12:30:45"};
        System.out.println(minDifference(arr));  
    }
}
Python
def toSeconds(time: str) -> int:
    
    # Convert time in "HH:MM:SS" format to total seconds.
    h = int(time[0:2])
    m = int(time[3:5])
    s = int(time[6:8])
    
    return h * 3600 + m * 60 + s

def minDifference(arr: list[str]) -> int:

    # Compute the minimum time difference 
    # between any two times in the array.
    seconds = [toSeconds(time) for time in arr]
    seconds.sort()
    
    minDiff = float('inf')
    n = len(seconds)

    # Compare adjacent elements
    for i in range(1, n):
        diff = seconds[i] - seconds[i - 1]
        minDiff = min(minDiff, diff)

    # Handle wrap-around difference 
    # between last and first
    wrapDiff = 86400 - seconds[-1] + seconds[0]
    minDiff = min(minDiff, wrapDiff)

    return minDiff

if __name__ == "__main__":
    arr = ["12:30:15", "12:30:45"]
    result = minDifference(arr)
    print(result)  
C#
using System;

class GfG{
    // Convert "HH:MM:SS" to total seconds
    private static int ToSeconds(string time){
        
        int h = int.Parse(time.Substring(0, 2));
        int m = int.Parse(time.Substring(3, 2));
        int s = int.Parse(time.Substring(6, 2));
        
        return h * 3600 + m * 60 + s;
    }

    // Find the minimum time difference in seconds
    public static int MinDifference(string[] arr){
        
        int n = arr.Length;
        int[] seconds = new int[n];

        // Convert all time strings to seconds
        for (int i = 0; i < n; i++)
        {
            seconds[i] = ToSeconds(arr[i]);
        }

        Array.Sort(seconds);

        int minDiff = int.MaxValue;

        // Compare adjacent elements
        for (int i = 1; i < n; i++){
            int diff = seconds[i] - seconds[i - 1];
            if (diff < minDiff){
                minDiff = diff;
            }
        }

        // Handle circular wrap-around 
        // last and first
        int wrapDiff = 86400 - seconds[n - 1] + seconds[0];
        if (wrapDiff < minDiff){
            minDiff = wrapDiff;
        }

        return minDiff;
    }

    static void Main(){

        string[] arr = { "12:30:15", "12:30:45" };
        int result = MinDifference(arr);
        Console.WriteLine(result);  
    }
}
JavaScript
// Convert "HH:MM:SS" to total seconds
function toSeconds(time) {
    const h = parseInt(time.slice(0, 2), 10);
    const m = parseInt(time.slice(3, 5), 10);
    const s = parseInt(time.slice(6, 8), 10);
    return h * 3600 + m * 60 + s;
}

// Find the minimum time difference in seconds
function minDifference(arr) {
    
    const seconds = arr.map(toSeconds);
    seconds.sort((a, b) => a - b);  

    let minDiff = Infinity;
    const n = seconds.length;

    // Compare adjacent time points
    for (let i = 1; i < n; i++) {
        const diff = seconds[i] - seconds[i - 1];
        minDiff = Math.min(minDiff, diff);
    }

    // Handle circular wrap-around 
    // last and first
    const wrapDiff = 86400 - seconds[n - 1] + seconds[0];
    minDiff = Math.min(minDiff, wrapDiff);

    return minDiff;
}

// Driver Code
const arr = ["12:30:15", "12:30:45"];
const result = minDifference(arr);
console.log(result);  

Output
30

[Expected Approach] Fixed-size Bucket Sort

The main Idea is to Map each time to a unique second of the day (0–86399) and track which seconds are used. Since there are only 86,400 possible seconds in a day, we can use a fixed-size array to efficiently check for duplicates and compute the smallest gap between any two times, treating the day as circular.

C++
#include <iostream>
#include <vector>
#include <string>
#include <climits>
#include <algorithm>
using namespace std;

// Convert "HH:MM:SS" to total 
// seconds since midnight
int toSeconds(string &time) {
    int h = stoi(time.substr(0, 2));
    int m = stoi(time.substr(3, 2));
    int s = stoi(time.substr(6, 2));
    return h * 3600 + m * 60 + s;
}

int minDifference(vector<string> &arr) {
    int totalSec = 24 * 3600;

    // Boolean array to mark seen
    // seconds size = 86400
    vector<bool> seen(totalSec, false);

    int n = arr.size();

    // Mark all seconds in the seen 
    // array, return 0 on duplicate
    for (int i = 0; i < n; i++) {
        int sec = toSeconds(arr[i]);
        if (seen[sec] == true) {
            return 0;
        }
        seen[sec] = true;
    }

    int first = -1;
    int last = -1;
    int prev = -1;
    int minDiff = INT_MAX;

    // finding minimum difference 
    // between adjacent times
    for (int i = 0; i < totalSec; i++) {
        if (!seen[i]) {
            continue;
        }
        if (prev != -1) {
            minDiff = min(minDiff, i - prev);
        } else {
            first = i;
        }
        prev = i;
        last = i;
    }

    // wrap-around difference 
    // between last and first
    int wrap = first + totalSec - last;
    minDiff = min(minDiff, wrap);

    return minDiff;
}

int main() {
    vector<string> arr = {"12:30:15", "12:30:45"};
    cout << minDifference(arr);
}
Java
class GfG {

    // Convert "HH:MM:SS" to total 
    // seconds since midnight
    private static int toSeconds(String time) {
        int h = Integer.parseInt(time.substring(0, 2));
        int m = Integer.parseInt(time.substring(3, 5));
        int s = Integer.parseInt(time.substring(6, 8));
        return h * 3600 + m * 60 + s;
    }

    public static int minDifference(String[] arr) {
        int totalSec = 24 * 3600;

        // Boolean array to mark seen
        // seconds size = 86400
        boolean[] seen = new boolean[totalSec];

        int n = arr.length;

        // Mark all seconds in the seen 
        // array, return 0 on duplicate
        for (int i = 0; i < n; i++) {
            int sec = toSeconds(arr[i]);
            if (seen[sec]) {
                return 0;
            }
            seen[sec] = true;
        }

        int first = -1;
        int last = -1;
        int prev = -1;
        int minDiff = Integer.MAX_VALUE;

        // finding minimum difference 
        // between adjacent times
        for (int i = 0; i < totalSec; i++) {
            if (!seen[i]) {
                continue;
            }
            if (prev != -1) {
                minDiff = Math.min(minDiff, i - prev);
            } else {
                first = i;
            }
            prev = i;
            last = i;
        }

        // wrap-around difference 
        // between last and first
        int wrap = first + totalSec - last;
        minDiff = Math.min(minDiff, wrap);

        return minDiff;
    }

    public static void main(String[] args) {
        String[] arr = {"12:30:15", "12:30:45"};
        int result = minDifference(arr);
        System.out.println(result);  
    }
}
Python
# Convert "HH:MM:SS" to total seconds since midnight
def toSeconds(time: str) -> int:
    
    h = int(time[0:2])
    m = int(time[3:5])
    s = int(time[6:8])

    return h * 3600 + m * 60 + s

def minDifference(arr: list[str]) -> int:
    totalSec = 24 * 3600

    # Boolean array to mark seen
    # seconds size = 86400
    seen = [False] * totalSec

    n = len(arr)

    # Mark all seconds in the seen 
    # array, return 0 on duplicate
    for i in range(n):
        sec = toSeconds(arr[i])
        if seen[sec]:
            return 0
        seen[sec] = True

    first = -1
    last = -1
    prev = -1
    minDiff = float('inf')

    # finding minimum difference 
    # between adjacent times
    for i in range(totalSec):
        if not seen[i]:
            continue
        if prev != -1:
            minDiff = min(minDiff, i - prev)
        else:
            first = i
        prev = i
        last = i

    # wrap-around difference 
    # between last and first
    wrap = first + totalSec - last
    minDiff = min(minDiff, wrap)

    return minDiff

if __name__ == "__main__":
    arr = ["12:30:15", "12:30:45"]
    result = minDifference(arr)
    print(result) 
C#
using System;

class GfG{
    
    // Convert "HH:MM:SS" to total seconds since midnight
    private static int ToSeconds(string time){
        
        int h = int.Parse(time.Substring(0, 2));
        int m = int.Parse(time.Substring(3, 2));
        int s = int.Parse(time.Substring(6, 2));
        
        return h * 3600 + m * 60 + s;
    }

    public static int minDifference(string[] arr){
        
        int totalSec = 24 * 3600;

        // Boolean array to mark seen seconds size = 86400
        bool[] seen = new bool[totalSec];

        int n = arr.Length;

        // Mark all seconds in the seen 
        // array, return 0 on duplicate
        for (int i = 0; i < n; i++){
            int sec = ToSeconds(arr[i]);
            if (seen[sec]){
                return 0;
            }
            seen[sec] = true;
        }

        int first = -1;
        int last = -1;
        int prev = -1;
        int minDiff = int.MaxValue;

        // finding minimum difference between adjacent times
        for (int i = 0; i < totalSec; i++){
            if (!seen[i]){
                continue;
            }
            if (prev != -1){
                minDiff = Math.Min(minDiff, i - prev);
            }
            else{
                first = i;
            }
            prev = i;
            last = i;
        }

        // wrap-around difference between last and first
        int wrap = first + totalSec - last;
        minDiff = Math.Min(minDiff, wrap);

        return minDiff;
    }

    static void Main(){
        string[] arr = { "12:30:15", "12:30:45" };
        int result = minDifference(arr);
        Console.WriteLine(result);  
    }
}
JavaScript
// Convert "HH:MM:SS" to total 
// seconds since midnight
function toSeconds(time) {
    
    const h = parseInt(time.slice(0, 2), 10);
    const m = parseInt(time.slice(3, 5), 10);
    const s = parseInt(time.slice(6, 8), 10);
   
    return h * 3600 + m * 60 + s;
}

function minDifference(arr) {
    const totalSec = 24 * 3600;

    // Boolean array to mark seen seconds size = 86400
    const seen = new Array(totalSec).fill(false);

    const n = arr.length;

    // Mark all seconds in the seen array, return 0 on duplicate
    for (let i = 0; i < n; i++) {
        const sec = toSeconds(arr[i]);
        if (seen[sec]) {
            return 0;
        }
        seen[sec] = true;
    }

    let first = -1;
    let last = -1;
    let prev = -1;
    let minDiff = Infinity;

    // finding minimum difference 
    // between adjacent times
    for (let i = 0; i < totalSec; i++) {
        if (!seen[i]) {
            continue;
        }
        if (prev !== -1) {
            minDiff = Math.min(minDiff, i - prev);
        } else {
            first = i;
        }
        prev = i;
        last = i;
    }

    // wrap-around difference 
    // between last and first
    const wrap = first + totalSec - last;
    minDiff = Math.min(minDiff, wrap);

    return minDiff;
}

// Driver Code
const arr = ["12:30:15", "12:30:45"];
const result = minDifference(arr);
console.log(result); 

Output
30

Time Complexity: O(n)
Auxiliary Space: O(1), because seen is a fixed-size array (constant size = 86400).

Comment