Latest Time by Replacing Hidden Digits

The problem asks for replacing the hidden digits in the given time to make it the latest possible valid time. The hidden digits are represented by ‘?’. We know that the valid times are inclusively between 00:00 and 23:59.

We can solve this problem by examining each character of the time string from left to right.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def maximumTime(self, time: str) -> str:
        time = list(time)

        if time[0] == '?':
            if time[1] not in {'0', '1', '2', '3', '?'}:
                time[0] = '1'
            else:
                time[0] = '2'

        if time[1] == '?':
            if time[0] == '2':
                time[1] = '3'
            else:
                time[1] = '9'

        if time[3] == '?':
            time[3] = '5'

        if time[4] == '?':
            time[4] = '9'
        
        return ''.join(time)

In this code, we first convert the input string time into a list so that we can modify its characters.

We then check each character in the time list:

  1. If the first character is ‘?’, it can be ‘2’ only if the second character is less than ‘4’. Otherwise, it should be ‘1’.
  2. If the second character is ‘?’, it can be ‘3’ if the first character is ‘2’. Otherwise, it should be ‘9’ to make the time latest.
  3. The third character can be a maximum of ‘5’ to be a valid minute.
  4. The fourth character can be a maximum of ‘9’ to make the minute the latest.

Finally, we join the characters in the time list to form a string and return it.