Skip to main content
Back to problems
#3114
Easy Algorithms

Latest time you can obtain after replacing characters

String Enumeration
35.1% acceptance
Feb 23, 2026
118
50
You are given a string s representing a 12-hour format time where some of the digits (possibly none) are replaced with a "?". 12-hour times are formatted as "HH:MM", where HH is between 00 and 11, and MM is between 00 and 59. The earliest 12-hour time is 00:00, and the latest is 11:59. 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.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_latest_time(s: String) -> String {
    let mut b = s.into_bytes();

    // Minutes: position 3 and 4
    if b[4] == b'?' {
      b[4] = b'9';
    }
    if b[3] == b'?' {
      b[3] = b'5';
    }

    // Hours: positions 0 and 1 (HH in 00..=11)
    match (b[0], b[1]) {
      (b'?', b'?') => {
        b[0] = b'1';
        b[1] = b'1';
      }
      (b'?', d) => {
        b[0] = if d <= b'1' { b'1' } else { b'0' };
      }
      (d, b'?') => {
        b[1] = if d == b'1' { b'1' } else { b'9' };
      }
      _ => {}
    }

    String::from_utf8(b).unwrap()
  }
}