Next Closest Time

We can simulate the clock going forward by one minute at a time, and we’ll check whether the current time can be represented by the digits in the input time. We’ll continue doing this until we find the next valid time. Here’s the step-by-step process:

  1. Parse the Input: Extract the digits from the input time, and store them in a set for quick access.
  2. Initialize Current Time: Start from the given time.
  3. Increment Time: Increment the time by one minute, and wrap around to “00:00” if we pass “23:59”.
  4. Check Validity: Check if the new time consists of the same digits as the given time.
  5. Repeat: Repeat steps 3-4 until we find the valid time.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def nextClosestTime(self, time: str) -> str:
        # Convert the input time to hours and minutes
        hours, minutes = map(int, time.split(":"))

        # Extract the unique digits from the given time
        allowed_digits = set(time[:2] + time[3:])

        # Simulate the clock going forward
        while True:
            # Increment the minutes by 1, and handle the overflow
            minutes += 1
            if minutes == 60:
                minutes = 0
                hours += 1
                if hours == 24:
                    hours = 0

            # Format the current time as "HH:MM"
            current_time = "{:02d}:{:02d}".format(hours, minutes)

            # Check if the current time consists of the same digits as the given time
            if set(current_time[:2] + current_time[3:]).issubset(allowed_digits):
                return current_time

The time complexity of this code is (O(1)) since the while loop will run at most 1440 times (the number of minutes in a day), and the space complexity is also (O(1)).