Sponsored
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.
Time Complexity: O(n log n) due to sorting where n is the number of time points. Space Complexity: O(n) since we store the times in minutes.
1def time_to_minutes(time):
2 hours, minutes = map(int, time.split(':'))
3 return hours * 60 + minutes
4
5def find_min_difference(time_points):
6 minutes = [time_to_minutes(time) for time in time_points]
7 minutes.sort()
8 min_diff = float('inf')
9 for i in range(1, len(minutes)):
10 min_diff = min(min_diff, minutes[i] - minutes[i - 1])
11 wrap_around_diff = minutes[0] + 1440 - minutes[-1]
12 min_diff = min(min_diff, wrap_around_diff)
13 return min_diff
14
15# Example usage
16time_points = ["23:59", "00:00"]
17print(find_min_difference(time_points))
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.
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.
Time Complexity: O(n + M), where M is 1440, the number of minutes in a day, n is the length of list.
Space Complexity: O(M), M = 1440, fixed.
1#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;
}
The C++ solution utilizes a boolean vector to monitor occupied minutes, efficiently calculating the smallest gap between true values, addressing the midnight lapse explicitly.