456/670

456. Next Closest Time

Medium

You are given a clock reading time as a string in 24-hour "HH:MM" format. Using only the digits that already appear in time — each digit may be reused as many times as you like — form the reading that comes soonest strictly after the given moment, wrapping past midnight when necessary.

Return that reading as an "HH:MM" string. If the input's digits cannot spell any other valid time, the soonest strictly-later occurrence is the same reading one full day later, so return the input unchanged (for example, "11:11" returns "11:11").

Example 1:

Input: time = "19:34"

Output: "19:39"

Explanation: The available digits are {1, 9, 3, 4}. Five minutes later, 19:39, uses only those digits; 19:33 is earlier, not later, and everything between 19:35 and 19:38 needs a digit that isn't available.

Example 2:

Input: time = "23:59"

Output: "22:22"

Explanation: With digits {2, 3, 5, 9}, no valid reading exists later the same day, so the clock wraps past midnight; the earliest reading the next day is 22:22.

Constraints:

  • time has the form "HH:MM" and is a valid 24-hour reading
  • 00 ≤ HH ≤ 23, 00 ≤ MM ≤ 59

Hints:

A clock only has 1,440 distinct minutes. What if you simply tick the time forward one minute at a time and check whether each reading uses only allowed digits? At most one full lap ends the search.

Alternatively, the input holds at most 4 distinct digits, so there are at most 4^4 = 256 candidate readings. Generate all of them, drop invalid hours/minutes, and pick the candidate with the smallest positive forward distance: delta = (candidate − current + 1440) mod 1440, counting delta 0 as a full day (1440).

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: time = "19:34"

Expected output: "19:39"