Given a time in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.
You may assume the input string is always valid. For example, "01:34" and "12:09" are valid, while "1:34" and "12:9" are not.
If the next closest time falls on the next day, wrap around. For example, the next closest time after "23:59" is "22:22" on the following day.
Function Signature
def next_closest_time(time: str) -> str:
Rules
-
A valid time has hours from
00
to
23
and minutes from
00
to
59
, written with two digits each.
-
Every digit of the result must be one of the digits in the input. Each digit may be used any number of times.
-
The result is the valid time that comes strictly after the input with the fewest minutes between them, counting forward and wrapping past midnight.
-
If no other valid time can be formed, return the input itself (the same time on the next day).
Constraints
-
len(time) == 5
and
time[2] == ":"
.
-
The input is a valid time in
"HH:MM"
format.
-
The result must also be a valid time in
"HH:MM"
format.
Examples
Input: time = "19:34"
Output: "19:39"
The digits are 1, 9, 3 and 4. The times 19:35 to 19:38 each need a digit that is not available, so the next one is 19:39, which reuses the 9 in the minutes.
Input: time = "23:59"
Output: "22:22"
The digits are 2, 3, 5 and 9. No valid time later on the same day can be formed, so the answer wraps to the earliest valid time of the next day. The only valid hours are 22 and 23, and the smallest minutes are 22.
Input: time = "11:11"
Output: "11:11"
The only digit is 1, so 11:11 is the only time that can be formed. The next occurrence is the same time on the next day.