Skip to main content
Back to problems
Leetcode
Medium
Strings
Greedy
Latest Time You Can Obtain After Replacing Characters

Fill the wildcards in a time string to make the latest valid 24-hour time.

Acceptance 0%
Problem Statement

You are given a time string in 24-hour format, written as hh:mm. Some characters are replaced with ?.

Replace each ? with a digit so that the resulting string is a valid time from 00:00 to 23:59. Among all valid replacements, return the one representing the latest time in the day.

A valid time must satisfy:

  • 00 <= hh <= 23
  • 00 <= mm <= 59

If multiple valid times are possible, choose the lexicographically largest time string, which is equivalent to the latest time.

Goal

Construct the latest valid time by choosing digits for all wildcards.

Input Format

  • A single string time of length 5 in the form hh:mm.
  • Each position is either a digit or ?.
  • The colon : is fixed.

Output Format

  • Return a string of length 5 representing the latest valid 24-hour time obtainable by replacing all ? characters.

Constraints

  • time.length = 5
  • time[2] = ':'
  • Each other character is either a digit or ?
  • The resulting time must be a valid 24-hour time
Examples
Sample cases returned by the problem API.

Example 1

Input

time = "2?:?0"

Output

"23:50"

Explanation

The latest valid hour starting with 2 is 23, and the latest valid minute ending in 0 is 50.

Example 2

Input

time = "0?:3?"

Output

"09:39"

Explanation

The hour can be made as large as possible while staying valid: 09. The minute can then be maximized to 39.

Show 1 more example

Example 3

Input

time = "??:??"

Output

"23:59"

Explanation

All positions are wildcards, so the latest possible time is 23:59.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.