LeetCode 681: Next Closest Time Solution
Master LeetCode problem 681 (Next Closest Time), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
681. Next Closest Time
Problem Explanation
Explanation:
Given a time represented in the format "HH:MM", we need to find the next closest time by reusing the digits of the input time. The next time should be greater than the input time. If there is no such time, we need to use the smallest possible time.
To solve this problem, we can iterate through all the possible times in a 24-hour clock (00:00 to 23:59) and check if all the digits of the new time are present in the original time. We start iterating from the next minute after the input time and keep checking until we find a valid time.
Algorithm:
- Parse the input time to extract the hours and minutes.
- Start iterating from the next minute after the input time.
- For each minute, check if all the digits are present in the original time.
- If a valid time is found, return it.
Time Complexity:
The time complexity of this algorithm is O(1) since we are iterating through a fixed number of minutes in a day.
Space Complexity:
The space complexity is O(1) as we are using a constant amount of extra space.
:
Solution Code
class Solution {
public String nextClosestTime(String time) {
Set<Character> digits = new HashSet<>();
for (char c : time.toCharArray()) {
if (c != ':') {
digits.add(c);
}
}
int hours = Integer.parseInt(time.substring(0, 2));
int minutes = Integer.parseInt(time.substring(3));
while (true) {
minutes++;
if (minutes == 60) {
minutes = 0;
hours = (hours + 1) % 24;
}
String nextTime = String.format("%02d:%02d", hours, minutes);
boolean valid = true;
for (char c : nextTime.toCharArray()) {
if (c != ':') {
if (!digits.contains(c)) {
valid = false;
break;
}
}
}
if (valid) {
return nextTime;
}
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 681 (Next Closest Time)?
This page provides optimized solutions for LeetCode problem 681 (Next Closest Time) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 681 (Next Closest Time)?
The time complexity for LeetCode 681 (Next Closest Time) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 681 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 681 in Java, C++, or Python.