We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Latest Time You Can Obtain After Replacing Characters

Difficulty: Easy


Problem Description

You are given a string s representing a 12-hour format time where some of the digits (possibly none) are replaced with a "?". You have to replace all the "?" characters in s with digits such that the time we obtain by the resulting string is a valid 12-hour format time and is the latest possible. Return the resulting string.


Key Insights

  • The string format is "HH:MM" where HH is between "00" and "11" and MM is between "00" and "59".
  • The goal is to maximize the time while ensuring that the resulting string is a valid time format.
  • Replacing "?" must be done strategically to ensure that both hours and minutes remain within their valid ranges.

Space and Time Complexity

Time Complexity: O(1) - The length of the string is constant (5 characters). Space Complexity: O(1) - Only a few variables are used for storage.


Solution

To solve the problem, we will follow these steps:

  1. Parse the string based on its fixed structure, focusing on the hour and minute components.
  2. For the hour component:
    • If the first character is "?", we will replace it with "1" if the second character is not "2" (to ensure the hour is 10 or 11). Otherwise, we will replace it with "0".
    • If the second character is "?", we will replace it with "1" if the first character is "1", and "9" if the first character is "0" or "?".
  3. For the minute component:
    • Replace the first character with "5" if it is "?".
    • Replace the second character with "9" if it is "?".
  4. Construct the resulting time string and return it.

Code Solutions

def latestTime(s: str) -> str:
    hours, minutes = s.split(':')
    
    # Handle hours
    if hours[0] == '?':
        if hours[1] == '?' or hours[1] < '2':
            hours = '1' + (hours[1] if hours[1] != '?' else '1')
        else:
            hours = '0' + (hours[1] if hours[1] != '?' else '0')
    if hours[1] == '?':
        if hours[0] == '1':
            hours = hours[0] + '1'  # 11 is the max for 1x
        else:
            hours = hours[0] + '9'  # max for 0x is 09

    # Handle minutes
    if minutes[0] == '?':
        minutes = '5' + (minutes[1] if minutes[1] != '?' else '9')
    if minutes[1] == '?':
        minutes = (minutes[0] if minutes[0] != '?' else '5') + '9'

    return hours + ':' + minutes
← Back to All Questions