# Program to find nearest time by reusing same digits of given time in python

Suppose we have a 24-hour string in "hh:mm" format, we have to find the next closest time that can be formed by reusing given digits. We can reuse digits from the given string as many times as we want.

So, if the input is like s = "03:15", then the output will be 03:30, as the nearest time 03:30 that repeats the given digits.

To solve this, we will follow these steps:

• use := a list with two digit hour and two digit mins values
• possible := a new set
• Define a function backtrack() . This will take path
• if size of path is same as 4, then
• (path[first two digit] concatenate ":" concatenate path[last two digits]) and insert it into possible.
• return
• for each p in use, do
• if (size of path is same as 0 and p > "2") is false and (path is same as "2" and p > "3") is false and (size of path is same as 2 and p > "5") is false, then
• backtrack(path + p)
• From the main method do the following:
• backtrack(blank string)
• possible := a new list from possible
• sort the list possible
• for i in range 0 to size of possible - 2, do
• if possible[i] is same as s, then
• return possible[i + 1]
• return possible

Let us see the following implementation to get better understanding:

## Example

Live Demo

class Solution:
def solve(self, s):
use = [s, s, s, s]
possible = set()

def backtrack(path):
nonlocal possible, use
if len(path) == 4:
return
for p in use:
if (not (len(path) == 0 and p > "2") and not (path == "2" and p > "3") and not (len(path) == 2 and p > "5")):
backtrack(path + p)

backtrack("")
possible = list(possible)
possible.sort()
for i in range(len(possible) - 1):
if possible[i] == s:
return possible[i + 1]
return possible

ob = Solution()
s = "03:15"
print(ob.solve(s))

## Input

"03:15"

## Output

03:30