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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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 < '2', then

• max_time := '9'

• if '9' >= max_time > '3', then

• max_time := '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 < '2':
max_time = '9'
if '9' >= max_time > '3':
max_time = '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