algoadvance

You are given a string time in the format HH:MM representing the latest possible time you could produce by changing at most 2 characters from the initial time. Return the latest possible time you can get.

For example:

Clarifying Questions:

  1. Do we always guarantee that the format will be HH:MM?
    • Yes.
  2. Are the : and all non-? characters valid digits for a time?
    • Yes, any non-? characters will be valid digits.

Strategy:

  1. For the first character (time[0]), determine if it’s ?. If it is, consider the constraints based on the second character (time[1]).
    • If time[1] is between 0-3 or ?, set time[0] to 2.
    • Otherwise, set time[0] to 1.
  2. For the second character (time[1]), if it’s ?:
    • If time[0] is 2, set it to 3.
    • Otherwise, set it to 9.
  3. For the third character, it’s always : and does not need modification.
  4. For the fourth character (time[3]), if it’s ?, set it to 5 (latest possible for tens of minutes).
  5. For the fifth character (time[4]), if it’s ?, set it to 9 (latest possible for units of minutes).

Code:

def latestTime(time: str) -> str:
    # Convert string to a list of characters for easier manipulation
    time = list(time)
    
    # Determine the maximum hour
    if time[0] == '?':
        if time[1] == '?' or time[1] < '4':
            time[0] = '2'
        else:
            time[0] = '1'
    
    if time[1] == '?':
        if time[0] == '2':
            time[1] = '3'
        else:
            time[1] = '9'
    
    # The ':' character does not change, so time[2] is untouched
    
    # Determine the maximum minute for tens place
    if time[3] == '?':
        time[3] = '5'
    
    # Determine the maximum minute for units place
    if time[4] == '?':
        time[4] = '9'
    
    # Convert list of characters back to string
    return ''.join(time)

# Example usage
print(latestTime("2?:?0"))  # Output: "23:50"
print(latestTime("0?:3?"))  # Output: "09:39"
print(latestTime("1?:22"))  # Output: "19:22"
print(latestTime("?4:5?"))  # Output: "14:59"

Time Complexity:

Try our interview co-pilot at AlgoAdvance.com