
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Nearest Time by Reusing Same Digits 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)
- 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
- 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]
- if possible[i] is same as s, then
- return possible[0]
Let us see the following implementation to get better understanding:
Example
class Solution: def solve(self, s): use = [s[0], s[1], s[3], s[4]] possible = set() def backtrack(path): nonlocal possible, use if len(path) == 4: possible.add(path[:2] + ":" + path[2:]) 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[0] ob = Solution() s = "03:15" print(ob.solve(s))
Input
"03:15"
Output
03:30
Advertisements