Find a lesson, question or project

Start typing to search published content and planned structures.

↑ ↓ moveEnter openEsc close

Next Closest Time in Java: Check the Next Minute, Not the Smallest Clock

Find the next time by bounded minute simulation, correctly handle midnight and unlimited digit reuse, and compare a recursive candidate generator.

MediumRecursion and backtrackingPattern: hashing

Problem statement

Given a valid 24-hour time in HH:MM format, find the next strictly later time using only its digits. A digit may be reused any number of times; it is an available alphabet, not a bag whose copies are consumed.

For 19:34 the answer is 19:39, five minutes later. Although 19:33 looks close on the clock, its next occurrence is tomorrow. For 23:59, the answer 22:22 is also tomorrow.

Hours are 00–23, minutes 00–59 and the input has exactly five characters. LeetCode Next Closest Time may require Premium. This explanation follows the supplied valid-input contract.

Constraints & requirements

CONTRACT
Fixed 24-hour clock: hours 00–23 and minutes 00–59. Search offsets 1–1440, not 0–1439. This bounded simulation is simpler than forcing recursion. LeetCode may require Premium.

Examples 3 test cases

  1. Example 1 Case 1

    Input
    "19:34"
    Output
    "19:39"

    The first five upcoming minutes end at an allowed-digit time.

  2. Example 2 Case 2

    Input
    "23:59"
    Output
    "22:22"

    The answer is on the next day, despite its smaller clock reading.

  3. Example 3 Case 3

    Input
    "11:11"
    Output
    "11:11"

    No earlier offset works; the same display next day is 1440 minutes later.

Solve on LeetCode ↗

Hints Optional

Hints become more specific one step at a time.
01Hint 1

There are only 1440 minutes in a day.

02Hint 2

Store a digit set, not digit frequencies.

03Hint 3

Advance in elapsed-minute order; the first valid display is the answer.

How to think before coding

The order to minimize is elapsed time, not the numeric HH:MM display. Convert the input to minutes, start the offset at ONE, and wrap modulo 1,440. Build a set of available digits: a digit may be reused, so frequencies are irrelevant. The first valid display is the answer, including the original display on the next day when nothing earlier works.

Brute force and the improvement

Enumerate all 1,440 clock displays. For each display using allowed digits, calculate its positive elapsed distance from the input, treating zero as 1,440 minutes, and keep the smallest distance. This is correct and uses constant space on a fixed 24-hour clock. The chosen method instead checks offsets 1..1,440 in order and returns at the first valid display. Both have the same fixed worst-case bound; the improvement is simpler stopping logic and possible early return, not a different asymptotic class.

Intuition: a small search can be the best design

There are only 1440 minutes in a day. Check them in future-time order and return the first display whose digits are allowed. After 1440 minutes, the original display recurs, so an answer is guaranteed.

This belongs beside recursive candidate-generation exercises, but your practice/NextClosestTime.java correctly uses a bounded simulation. Forcing recursion here adds complexity without improving the fixed-size search.

Algorithm

  1. Put the four input digits into a set, ignoring the colon.
  2. Convert the time into hours×60 + minutes.
  3. Check elapsed offsets 1 through 1440 inclusive.
  4. Wrap each new total with %1440.
  5. Format valid hour/minute values with leading zeros.
  6. Return the first display whose non-colon characters belong to the set.

Java solution

Locale.ROOT makes formatting independent of the machine’s locale. Valid input always finds a result within 1,440 minutes, including the same display on the next day.

Java
import java.util.*;

class Solution {
    public static String nextClosestTime(String time) {
        Set<Character> allowed = new HashSet<>();
        for (char ch : time.toCharArray()) if (ch != ':') allowed.add(ch); // Availability, not frequency.
        int start = Integer.parseInt(time.substring(0, 2)) * 60
                + Integer.parseInt(time.substring(3, 5)); // HH:MM becomes minutes since midnight.
        for (int delta = 1; delta <= 1440; delta++) { // Start strictly AFTER now; original returns next day.
            int next = (start + delta) % 1440; // Wrap at midnight instead of rejecting the next day.
            String candidate = String.format(Locale.ROOT, "%02d:%02d", next / 60, next % 60);
            if (usesAllowedDigits(candidate, allowed)) return candidate; // First valid minute is closest.
        }
        throw new IllegalStateException("The original valid time must recur within one day");
    }
    private static boolean usesAllowedDigits(String time, Set<Character> allowed) {
        for (char ch : time.toCharArray()) {
            if (ch != ':' && !allowed.contains(ch)) return false; // Repeated allowed digits remain legal.
        }
        return true; // Every digit belongs to the original digit set.
    }

    public static void main(String[] args) {
        System.out.println(nextClosestTime("19:34")); // 19:39
    }
}

The default invocation returns 19:39. When only digit 1 is available, 11:11 is returned after a full day, not treated as the current instant.

Timeline and dry run

Numbered illustrated dry run for Next Closest Time; the text transcript explains the states.
Follow the numbered panels in order. Open full-size dry run ↗
Read the text transcript

Follow the Java, step by step

Example: time = "19:34"

What to track: allowed = {1,9,3,4}; start = 1174 minutes. This maintained solution scans elapsed minutes; it is not a recursive DFS.

  1. Begin strictly after the input

    Java operationint next = (start + delta) % 1440;
    Statedelta = 1; next = 1175; candidate = "19:35"

    A candidate is always a valid clock time because it is built from minutes modulo one day.

  2. Reject the first new digit

    Java operationif (ch != ':' && !allowed.contains(ch)) return false;
    Statecandidate "19:35" contains 5, which is not in allowed

    The helper returns false; the outer loop advances to the next elapsed minute.

  3. Continue in chronological order

    Java operationfor (int delta = 1; delta <= 1440; delta++)
    Statedelta = 2,3,4 produce "19:36", "19:37", "19:38"; each fails on its last digit

    No legal earlier candidate was skipped. The original input is not returned at delta = 0.

  4. Return the first legal minute

    Java operationif (usesAllowedDigits(candidate, allowed)) return candidate;
    Statedelta = 5; candidate = "19:39"; every displayed digit belongs to allowed

    9 can be reused; the rule concerns digit availability, not how many copies appeared originally.

Final result: "19:39", five minutes later.

Elapsed minutes Candidate Decision
1 19:35 Reject 5
2 19:36 Reject 6
3 19:37 Reject 7
4 19:38 Reject 8
5 19:39 All digits in {1,3,4,9}; return

For 23:59, +1 gives 00:00, but 0 is unavailable. Eventually +1343 minutes gives tomorrow’s 22:22, which uses only allowed digits. The modulo converts the clock display; the offset retains chronological meaning.

Why it works

Offsets are checked in increasing positive order, so no earlier future candidate is skipped. Each candidate is a valid clock time because it is derived from a minute total in 0–1439. Digit validation enforces exactly the reuse rule. The first passing display is therefore the closest, and the original valid time supplies a passing candidate by offset 1440.

Complexity and alternative approaches

The fixed 24-hour problem takes O(1440·4)=O(1) time and O(1) extra space. Calling it O(N) without defining a variable domain is misleading; input length is always five.

Another approach recursively chooses four positions from the D distinct allowed digits, exploring at most D^4 arrangements, where D≤4. Reject invalid hours/minutes, compute (candidate-start+1440)%1440, replace zero distance with 1440, and minimize positive elapsed distance. Reuse is allowed at every position; a used-index permutation array would enforce the wrong rule.

The minute scan has fewer concepts, needs no explicit minimum tracking and matches your solution. Candidate generation is a valid alternative, not a requirement to use recursion everywhere.

Common mistakes

  • Starting at offset 0 returns now instead of the next occurrence.
  • Stopping before 1440 misses the single-digit-alphabet case.
  • Using digit frequencies forbids legal repeated digits.
  • Minimizing the numeric HHMM value ignores elapsed time and midnight.
  • Dropping leading zeros creates a malformed display.

Practice next

Next lessonBrace Expansion

Back to Recursion and backtracking →