Program to find latest valid time by replacing hidden digits in Python


Suppose we have a string s represents time in the form of hh:mm. Some of the digits in s are hidden (represented by ?). Considering 24hr clock, the valid times are between 00:00 and 23:59. We have to find the latest valid time that we can get from time by replacing the hidden digits.

So, if the input is like s= "1?:?5", then the output will be 13:55 as the latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.

To solve this, we will follow these steps −

  • ans := a new list

  • max_time := ['2','3',':','5','9']

  • if max_time[0] < '2', then

    • max_time[1] := '9'

  • if '9' >= max_time[1] > '3', then

    • max_time[0] := '1'

  • for each pair (mx, digit) from (max_time, s), do

    • if digit is a single digit, then

      • insert digit at the end of ans

    • otherwise,

      • insert mx at the end of ans

  • join characters present in ans and return

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(s):
   ans = []
   max_time = ['2','3',':','5','9']
   if max_time[0] < '2':
      max_time[1] = '9'
   if '9' >= max_time[1] > '3':
      max_time[0] = '1'
   for mx,digit in zip(max_time,s):
      if digit.isdigit():
         ans.append(digit)
      else:
         ans.append(mx)
   return ''.join(ans)

s= "1?:?5"
print(solve(s))

Input

"1?:?5"

Output

13:55

Updated on: 18-May-2021

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements