1736. Latest Time by Replacing Hidden Digits

1736. Latest Time by Replacing Hidden Digits #

Problem #

You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).

The valid times are those inclusively between 00:00 and 23:59.

Return the latest valid time you can get from time by replacing the hidden digits.

Example 1:

Input: time = "2?:?0"
Output: "23:50"
Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.

Example 2:

Input: time = "0?:3?"
Output: "09:39"

Example 3:

Input: time = "1?:22"
Output: "19:22"

Constraints:

  • time is in the format hh:mm.
  • It is guaranteed that you can produce a valid time from the given string.

Problem Summary #

You are given a string time in the format hh:mm (hour:minute), where some digits are hidden (represented by ?). Valid times are all times between 00:00 and 23:59, inclusive. Replace the hidden digits in time and return the latest valid time you can obtain.

Solution Approach #

  • Easy problem. According to the problem statement, we need to find the latest valid time. Just enumerate the 4 positions of the time. If the 3rd position is ?, then its latest value is 5; if the 4th position is ?, then its latest value is 9; if the 2nd position is ?, then its latest value is 9; if the 1st position is ?, determine it based on the 2nd position: if the 2nd position is a number greater than 3, then the latest value for the first position is 1; if the 2nd position is a number less than 3, then the latest value for the first position is 2. Following the rules above restores the latest time.

Code #

package leetcode

func maximumTime(time string) string {
	timeb := []byte(time)
	if timeb[3] == '?' {
		timeb[3] = '5'
	}
	if timeb[4] == '?' {
		timeb[4] = '9'
	}
	if timeb[0] == '?' {
		if int(timeb[1]-'0') > 3 && int(timeb[1]-'0') < 10 {
			timeb[0] = '1'
		} else {
			timeb[0] = '2'
		}
	}
	if timeb[1] == '?' {
		timeb[1] = '9'
	}
	if timeb[0] == '2' && timeb[1] == '9' {
		timeb[1] = '3'
	}
	return string(timeb)
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文