LeetCode 681: Next Closest Time Solution in Python – A Step-by-Step Guide

Imagine you’re a time traveler with a clock showing "19:34", and your task is to find the next closest valid time—like "19:43"—using only the digits 1, 9, 3, and 4 from the original time, rearranging them as needed. That’s the puzzle of LeetCode 681: Next Closest Time, a medium-level problem that’s all about crafting a valid time from a limited set of digits while minimizing the time difference. Using Python, we’ll explore two solutions: the Best Solution, a digit permutation with validation approach for efficiency, and an Alternative Solution, a time increment with set check method that’s simpler but slower. With detailed examples, beginner-friendly breakdowns—especially for the permutation method—and clear code, this guide will help you time-travel to the next moment, whether you’re new to coding or leveling up. Let’s set that clock and start ticking!

What Is LeetCode 681: Next Closest Time?

Section link icon

In LeetCode 681: Next Closest Time, you’re given a string time in "HH:MM" format (e.g., "19:34"), representing a valid 24-hour time, and your task is to find the next closest valid time that can be formed by reusing the four digits in the original time (each digit from hours and minutes). The clock wraps around from "23:59" to "00:00", and you must return the result in "HH:MM" format. For example, with time = "19:34", using digits [1, 9, 3, 4], the next closest time is "19:43", a 9-minute difference. With time = "23:59", it wraps to "22:22" using [2, 3, 5, 9]. This problem tests your ability to manipulate digits and validate times efficiently.

Problem Statement

  • Input:
    • time: String in "HH:MM" format (valid 24-hour time).
  • Output: A string—next closest valid time in "HH:MM" format.
  • Rules:
    • Use only the four digits from time (HH and MM).
    • Form a valid 24-hour time (00:00 to 23:59).
    • Find the smallest time difference forward, wrapping at midnight.
    • Each digit can be reused as needed.

Constraints

  • time is a valid time in "HH:MM" format.
  • 0 ≤ HH ≤ 23, 0 ≤ MM ≤ 59.

Examples

  • Input: time = "19:34"
    • Output: "19:43" (Digits [1, 9, 3, 4], next valid time)
  • Input: time = "23:59"
    • Output: "22:22" (Digits [2, 3, 5, 9], wraps around)
  • Input: time = "00:00"
    • Output: "00:00" (Digits [0, 0, 0, 0], same time if no other option)

These examples set the clock—let’s solve it!

Understanding the Problem: Finding the Next Time

Section link icon

To solve LeetCode 681: Next Closest Time in Python, we need to find the next closest valid 24-hour time using only the four digits from the input time, minimizing the difference while handling the midnight wrap-around. A brute-force approach—generating all possible times and sorting—would be O(4⁴) for digit combinations, feasible but inefficient for a small set. Since we’re working with a fixed set of digits and time progression, we can optimize with permutations or incremental checks. We’ll use:

  • Best Solution (Digit Permutation with Validation): O(4⁴) time, O(1) space—fast and practical.
  • Alternative Solution (Time Increment with Set Check): O(n) time (n = minutes in a day), O(1) space—simple but slower.

Let’s start with the permutation solution, breaking it down for beginners.

Best Solution: Digit Permutation with Validation

Section link icon

Why This Is the Best Solution

The digit permutation with validation approach is the top choice for LeetCode 681 because it’s efficient—O(4⁴) time with O(1) space—and leverages the small, fixed set of four digits to generate all possible times, validate them, and find the next closest one directly. It fits constraints (fixed 4-digit input) perfectly and is intuitive once you see the permutation logic. It’s like shuffling the digits into every possible time and picking the next one on the clock!

How It Works

Think of this as a time shuffler:

  • Step 1: Extract Digits:
    • Get digits from time (e.g., "19:34" → [1, 9, 3, 4]).
  • Step 2: Generate All Times:
    • Use nested loops or permutations to form all HH:MM combinations.
  • Step 3: Validate Times:
    • Check if HH (00-23) and MM (00-59) are valid.
  • Step 4: Convert to Minutes:
    • Current time to minutes since 00:00.
    • Each valid time to minutes.
  • Step 5: Find Next Closest:
    • Calculate difference from current time, handle wrap-around.
    • Pick smallest positive difference.
  • Step 6: Return Result:
    • Format as "HH:MM".

It’s like a digit mixer—shuffle and pick!

Step-by-Step Example

Example: time = "19:34"

  • Step 1: Digits = [1, 9, 3, 4].
  • Step 2: Generate times (partial list):
    • 11:33, 11:34, 11:43, 11:44, 13:13, 13:14, ...
    • 19:13, 19:14, 19:31, 19:33, 19:34, 19:43, ...
    • 31:13, 31:14, 31:41, ...
  • Step 3: Validate:
    • Valid: 11:33, 11:34, 13:14, 19:13, 19:43, etc.
    • Invalid: 31:13 (HH > 23).
  • Step 4: Minutes:
    • Current = 19:34 = 19 * 60 + 34 = 1174.
    • Valid times (minutes):
      • 11:33 = 693, 11:34 = 694, 13:14 = 794, 19:13 = 1153, 19:43 = 1183.
  • Step 5: Differences:
    • Wrap-around day = 1440 minutes.
    • 693 - 1174 = -481 (+1440 = 959), 694 = 960, 794 = 1060, 1153 = -21, 1183 = 9.
    • Smallest positive = 9 (19:43).
  • Step 6: Return "19:43".
  • Output: "19:43".

Code with Detailed Line-by-Line Explanation

Here’s the Python code, explained clearly:

class Solution:
    def nextClosestTime(self, time: str) -> str:
        # Step 1: Extract digits
        digits = [int(d) for d in time if d != ':']
        curr_h, curr_m = int(time[:2]), int(time[3:])
        curr_minutes = curr_h * 60 + curr_m

        # Step 2: Generate all possible times
        min_diff = float('inf')
        next_time = None

        for h1 in digits:
            for h2 in digits:
                for m1 in digits:
                    for m2 in digits:
                        # Step 3: Validate time
                        hh = h1 * 10 + h2
                        mm = m1 * 10 + m2
                        if hh < 24 and mm < 60:
                            total_minutes = hh * 60 + mm
                            # Step 4: Calculate difference
                            diff = total_minutes - curr_minutes
                            if diff <= 0:  # Wrap around
                                diff += 24 * 60
                            # Step 5: Update if smallest positive diff
                            if 0 < diff < min_diff:
                                min_diff = diff
                                next_time = f"{h1}{h2}:{m1}{m2}"

        # Step 6: Return result (same time if no next found)
        return next_time if next_time else time
  • Lines 4-6: Extract: Get digits, convert current time to minutes.
  • Lines 9-11: Init: Track min difference and next time.
  • Lines 13-27: Generate and validate:
    • Nested loops for HH:MM, check validity, compute diff, update if closest.
  • Line 30: Return: Next time or original if none found.
  • Time Complexity: O(4⁴)—256 combinations (4 digits, 4 positions).
  • Space Complexity: O(1)—minimal extra space.

This is like a time crafter—permute and select!

Alternative Solution: Time Increment with Set Check

Section link icon

Why an Alternative Approach?

The time increment with set check approach increments minutes—O(n) time (n = 1440 minutes), O(1) space. It’s simpler, ticking forward and checking digit validity, but slower due to linear time traversal. It’s like winding the clock until the digits match!

How It Works

Picture this as a clock ticker:

  • Step 1: Get digit set from time.
  • Step 2: Convert to minutes, increment:
    • Start at current minutes, add 1 each step.
  • Step 3: Check validity:
    • Convert back to HH:MM, verify digits in set.
  • Step 4: Wrap around, return result.

It’s like a time stepper—tick and match!

Step-by-Step Example

Example: time = "19:34"

  • Step 1: Digit set = {1, 9, 3, 4}.
  • Step 2: Current = 1174 minutes.
    • 1175 (19:35): Digits [1, 9, 3, 5], 5 not in set.
    • 1176 (19:36): [1, 9, 3, 6], 6 not in set.
    • ...
    • 1183 (19:43): [1, 9, 4, 3], all in set, return.
  • Step 4: Return "19:43".
  • Output: "19:43".

Code for Increment Approach

class Solution:
    def nextClosestTime(self, time: str) -> str:
        # Step 1: Get digit set
        digits = set(time.replace(':', ''))
        curr_h, curr_m = int(time[:2]), int(time[3:])
        curr_minutes = curr_h * 60 + curr_m

        # Step 2: Increment minutes
        while True:
            curr_minutes = (curr_minutes + 1) % (24 * 60)  # Wrap around
            hh, mm = divmod(curr_minutes, 60)
            next_time = f"{hh:02d}:{mm:02d}"

            # Step 3: Check if all digits in set
            if all(digit in digits for digit in next_time if digit != ':'):
                return next_time
  • Lines 4-6: Extract: Digit set, current minutes.
  • Lines 9-15: Increment:
    • Add 1 minute, wrap at 1440, check digits against set.
  • Time Complexity: O(n)—n = 1440 minutes worst case.
  • Space Complexity: O(1)—digit set and variables.

It’s a clock winder—increment and verify!

Comparing the Two Solutions

Section link icon
  • Permutation (Best):
    • Pros: O(4⁴) time, O(1) space, fast with fixed cost.
    • Cons: Permutation logic less obvious.
  • Increment (Alternative):
    • Pros: O(n) time (n=1440), O(1) space, intuitive.
    • Cons: Slower for sparse digit sets.

Permutation wins for speed.

Additional Examples and Edge Cases

Section link icon
  • Input: time = "00:00"
    • Output: "00:00".
  • Input: time = "23:59"
    • Output: "22:22" (wraps).

Permutation handles these well.

Complexity Breakdown

Section link icon
  • Permutation: Time O(4⁴), Space O(1).
  • Increment: Time O(1440), Space O(1).

Permutation is optimal for fixed size.

Key Takeaways

Section link icon
  • Permutation: Digit shuffling—smart!
  • Increment: Time ticking—clear!
  • Clocks: Timing is fun.
  • Python Tip: Loops rock—see Python Basics.

Final Thoughts: Set That Clock

Section link icon

LeetCode 681: Next Closest Time in Python is a fun time challenge. Digit permutation with validation offers speed and precision, while time increment provides a clear alternative. Want more? Try LeetCode 539: Minimum Time Difference or LeetCode 682: Baseball Game. Ready to tick? Head to Solve LeetCode 681 on LeetCode and find that next time today!