Leetcode 1736: Latest Time by Replacing Hidden Digits

grid47
grid47
Exploring patterns and algorithms
May 17, 2024 7 min read

You are given a time string in the format hh:mm, where some digits may be missing and represented by a question mark (?). Your task is to replace the ? with digits to form the latest valid time in the 24-hour format, which is between 00:00 and 23:59.
Problem
Approach
Steps
Complexity
Input: The input is a string representing a time in the format `hh:mm`, where some digits may be hidden by `?` characters. The goal is to replace `?` with digits to form the latest valid time.
Example: Input: time = "1?:?4"
Constraints:
• The input time string is guaranteed to be in the format hh:mm.
• The digits of the input time can be replaced by valid digits to form a valid time.
Output: Return the latest valid time obtained by replacing the question marks in the input string with valid digits.
Example: Output: "19:54"
Constraints:
• The output is a valid time string in the format hh:mm.
Goal: The goal is to determine the latest valid time by replacing the `?` characters with the largest possible digits that form a valid time.
Steps:
• 1. Identify the valid range for the hour based on the first digit, considering if the second digit is `?`.
• 2. If the second digit is `?`, replace it with the largest possible value based on the first digit.
• 3. For the minutes part, replace any `?` with the largest valid digit (`5` for the tens place, `9` for the ones place).
• 4. Return the modified time string.
Goal: The following constraints hold for the problem:
Steps:
• The time string is always in the format hh:mm.
• Each `?` in the input string can be replaced with a digit that results in a valid time.
• The time must always be between `00:00` and `23:59`.
Assumptions:
• The input time string is guaranteed to be in a valid format and the solution always exists.
Input: Input: time = "2?:?0"
Explanation: The latest hour starting with '2' is '23', and the latest minute ending with '0' is '50'. Therefore, the result is '23:50'.

Input: Input: time = "0?:3?"
Explanation: The latest valid hour with '0' in the first digit can be '09'. The latest minute ending with '9' is '39'. Therefore, the result is '09:39'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus