Leetcode 2224. Minimum Number of Operations to Convert Time
You are given two strings current
and correct
representing two 24-hour times in the format “HH:MM.” The task is to determine the minimum number of operations required to convert current
to correct
. You can only perform the following operations:
Return the minimum number of operations needed to transform current
into correct
.
current
and correct
will be valid 24-hour format times?current
and correct
be the same initial times?current
and correct
times into the total number of minutes past midnight for easier comparison and manipulation.current
and correct
times.Here is the C++ code implementing the above strategy:
#include <iostream>
#include <string>
#include <cmath>
int convertTime(const std::string& current, const std::string& correct) {
// Helper function to convert "HH:MM" time format to minutes past midnight.
auto toMinutes = [](const std::string& time) {
int hours = std::stoi(time.substr(0, 2));
int minutes = std::stoi(time.substr(3, 2));
return hours * 60 + minutes;
};
int currentMinutes = toMinutes(current);
int correctMinutes = toMinutes(correct);
int difference = std::abs(correctMinutes - currentMinutes); // Ensure non-negative difference
int operations = 0;
int increments[] = {60, 15, 5, 1}; // Available increments
// Apply the maximum possible increment each time
for (int inc : increments) {
operations += difference / inc;
difference %= inc;
}
return operations;
}
// For test purposes
int main() {
std::string current = "02:30";
std::string correct = "04:35";
std::cout << "Minimum operations: " << convertTime(current, correct) << std::endl;
return 0;
}
The time complexity of this solution is O(1) because the number of operations is bounded by a constant (4 different increments) regardless of the input size. The main work — converting times and calculating operations — involves simple arithmetic and remains constant time.
By following this strategy, we ensure an optimal, efficient solution to convert the given time in the fewest number of operations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?