Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find nearest time by reusing same digits of given time in python
Given a 24-hour time string in "hh:mm" format, we need to find the next closest time that can be formed by reusing the same digits. We can reuse any digit from the original time as many times as needed.
For example, if the input is "03:15", the output will be "03:30" since it's the nearest valid time using only digits 0, 3, 1, and 5.
Algorithm Approach
We'll use backtracking to generate all possible valid times using the given digits, then find the next time in chronological order ?
- Extract all four digits from the input time
- Use backtracking to generate all valid 4−digit combinations
- Filter combinations that form valid times (hours ? 23, minutes ? 59)
- Sort all possible times and return the next one after the input
Implementation
class Solution:
def solve(self, s):
# Extract digits from the time string
digits = [s[0], s[1], s[3], s[4]]
possible_times = set()
def backtrack(path):
nonlocal possible_times, digits
# If we have formed a complete 4-digit time
if len(path) == 4:
time_str = path[:2] + ":" + path[2:]
possible_times.add(time_str)
return
# Try each available digit
for digit in digits:
# Check time validity constraints
if self.is_valid_position(path, digit):
backtrack(path + digit)
# Generate all possible times
backtrack("")
# Convert to sorted list
possible_times = sorted(list(possible_times))
# Find the next time after input
for i in range(len(possible_times) - 1):
if possible_times[i] == s:
return possible_times[i + 1]
# If input is the last time, return the first (next day)
return possible_times[0]
def is_valid_position(self, path, digit):
"""Check if adding digit at current position creates valid time"""
pos = len(path)
# First digit of hour: must be ? 2
if pos == 0 and digit > "2":
return False
# Second digit of hour: if first digit is 2, second must be ? 3
if pos == 1 and path == "2" and digit > "3":
return False
# First digit of minutes: must be ? 5
if pos == 2 and digit > "5":
return False
return True
# Test the solution
ob = Solution()
time_input = "03:15"
result = ob.solve(time_input)
print(f"Input: {time_input}")
print(f"Next closest time: {result}")
Input: 03:15 Next closest time: 03:30
How It Works
The algorithm works by:
- Digit Extraction: We extract digits [0, 3, 1, 5] from "03:15"
- Backtracking: Generate all 4−digit combinations like "0301", "0313", "0315", etc.
- Validation: Only keep combinations forming valid times (hours 00−23, minutes 00−59)
- Next Time: Sort all valid times and return the one immediately after the input
Example with Different Input
ob = Solution()
# Test with different time
test_cases = ["23:59", "12:34", "00:00"]
for time_str in test_cases:
result = ob.solve(time_str)
print(f"Input: {time_str} ? Next: {result}")
Input: 23:59 ? Next: 22:22 Input: 12:34 ? Next: 13:11 Input: 00:00 ? Next: 00:00
Time Complexity
The time complexity is O(4^4) = O(256) for generating combinations, plus sorting time. Since we're dealing with at most 1440 possible times in a day, the algorithm is very efficient.
Conclusion
This backtracking solution efficiently finds the next closest time by generating all valid combinations of the given digits. The key insight is validating time constraints during the backtracking process to avoid invalid times.
