VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-difference/

⇱ Minimize Difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

[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.


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.


Output
30

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

Comment
Article Tags:
Article Tags: