07. Difference Check
β GFG solution to the Minimum Time Difference problem: find minimum difference in seconds between any two time strings using efficient sorting technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an array arr[] of time strings in 24-hour clock format "HH:MM:SS". Your task is to find the minimum difference in seconds between any two time strings in the array.
The clock wraps around at midnight, so the time difference between "23:59:59" and "00:00:00" is 1 second.
π Examples
Example 1
Input: arr[] = ["12:30:15", "12:30:45"]
Output: 30
Explanation: The minimum time difference is 30 seconds.Example 2
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".π Constraints
$2 \le \text{arr.size()} \le 10^5$
$\text{arr}[i]$ is in "HH:MM:SS" format.
β
My Approach
The optimal approach uses Time Conversion and Sorting to efficiently find the minimum difference:
Time Parsing + Sorting Algorithm
Convert Time to Seconds:
Parse each time string "HH:MM:SS" and convert to total seconds from midnight.
Formula:
seconds = hours * 3600 + minutes * 60 + secondsThis normalizes all times to a single integer format for easy comparison.
Sort the Seconds:
Sort all converted time values in ascending order.
This allows us to check adjacent pairs for minimum differences efficiently.
Find Minimum Adjacent Differences:
Iterate through sorted array and calculate difference between consecutive elements.
Keep track of the minimum difference found.
Handle Circular Clock:
Consider the wrap-around case: difference between the last time and first time of next day.
Calculate:
first_time + 86400 - last_time(86400 = total seconds in a day).Compare this with other differences to find the global minimum.
Early Termination:
If any two times are identical, return 0 immediately.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n), where n is the size of the array. The time conversion takes O(n) time, but sorting dominates with O(n log n) complexity.
Expected Auxiliary Space Complexity: O(n), where n is the size of the array. We use additional space to store the converted seconds in a vector/array.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated