This problem asks to find the next closest time using only the digits present in the input time string. The solution uses a backtracking approach to explore all possible combinations of hours and minutes, and it efficiently determines the closest time.
Extract Digits: The solution first extracts the unique digits present in the input time string (time
).
Backtracking: A depth-first search (DFS) using backtracking explores all possible combinations of four digits. Each digit is chosen from the set of unique digits. The DFS function constructs potential times and checks their validity.
Validity Check: The check
function verifies if a generated time is valid (hours between 0 and 23, minutes between 0 and 59).
Closest Time: The solution keeps track of the closest valid time found so far. It calculates the difference in minutes between the current time and the potential times and updates the closest time if a closer valid time is encountered.
Handling No Closer Time: If no closer valid time is found (this can happen if the input time is "23:59"), the solution returns a time formed using the smallest digit available.
Time Representation: Time is represented as total minutes from midnight for easier comparison.
Time Complexity: O(4^4) ≈ O(1). The backtracking explores all possible 4-digit combinations from the available digits. Since the number of digits is limited, this complexity is effectively constant.
Space Complexity: O(1). The space used is constant, regardless of the input, as it only stores a small number of variables and a set of digits.
class Solution:
def nextClosestTime(self, time: str) -> str:
def check(t): #Checks if the time is valid
h, m = int(t[:2]), int(t[2:])
return 0 <= h < 24 and 0 <= m < 60
def dfs(curr): #Recursive function to find the closest time
if len(curr) == 4:
if not check(curr):
return
nonlocal ans, d # Accessing variables from the outer scope
p = int(curr[:2]) * 60 + int(curr[2:]) #Time in minutes
if t < p < t + d:
d = p - t
ans = curr[:2] + ':' + curr[2:]
return
for c in s: # Iterate through available digits
dfs(curr + c)
s = {c for c in time if c != ':'} # Unique digits
t = int(time[:2]) * 60 + int(time[3:]) # Current time in minutes
import sys
d = sys.maxsize # Initialize difference to maximum possible value
ans = None # Initialize answer to None
dfs('') # Start backtracking
if ans is None: # Handle case where no closer time is found
mi = min(int(c) for c in s)
ans = f'{mi}{mi}:{mi}{mi}'
return ans
The Java code follows a similar structure and logic, using Java's HashSet
for digit storage and Integer.parseInt
for converting string representations to integers. The core backtracking algorithm remains the same.
This detailed explanation clarifies the solution's approach, its implementation in Python and Java, and its performance characteristics. The backtracking strategy efficiently explores the limited search space, leading to a constant-time solution.