Problem 1736

Abstract / Summary

Replace hidden digits in a time string to make the latest possible valid time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1736.py

class Solution:
    def maximumTime(self, time: str) -> str:
        # pretty much brute-force
        regex = time.replace("?", ".")
        for hour in range(23, -1, -1):
            # match hour
            s = f"{hour:02d}"
            if not re.search(regex[:2], s):
                continue

            # match minute
            for minute in range(59, -1, -1):
                s = f"{hour:02d}:{minute:02d}"
                if re.search(regex, s):
                    return s
15 lines | 501 bytes | submitted October 12, 2023 | GitHub   27% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 44% (100k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method maximumTime that receives a time string containing digits and placeholder characters (?). The goal is to replace the placeholders with digits so that the resulting time is the latest possible valid 24-hour time. The implementation follows a straightforward search strategy that enumerates candidate hours and minutes in descending order, checking each candidate against the pattern derived from the input.

Core Logic

The method begins by converting the input pattern into a regular-expression-compatible form. All ? characters are replaced with . which matches any single character. This transformed pattern, stored in the variable regex, is used for subsequent matching.

regex = time.replace("?", ".")

The search proceeds with a loop over possible hour values from 23 down to 0. For each hour, the integer is formatted as a two-digit string using an f-string. The hour portion of the pattern (the first two characters) is then matched against this formatted hour using re.search. If the hour does not satisfy the pattern, the loop continues to the next lower hour, effectively pruning large portions of the search space early.

for hour in range(23, -1, -1):
    s = f"{hour:02d}"
    if not re.search(regex[:2], s):
        continue

When a matching hour is found, a nested loop iterates over minute values from 59 down to 0. Each minute is also formatted as a two-digit string and combined with the previously selected hour to form a full time string in the HH:MM format. The complete pattern regex is then applied to this full string. The first full match encountered is the maximum valid time, and the method returns it immediately.

    for minute in range(59, -1, -1):
        s = f"{hour:02d}:{minute:02d}"
        if re.search(regex, s):
            return s

Edge Cases Handled

The algorithm correctly processes inputs where the hour or minute fields contain one or more placeholders. Because the hour loop starts at the highest possible value (23) and the minute loop starts at 59, any combination that satisfies the pattern will be the latest possible time. The use of f"{hour:02d}" and f"{minute:02d}" guarantees that single-digit values are padded with a leading zero, ensuring proper matching against patterns like "0?" or "?5".

When the input contains no placeholders, the regular expression becomes an exact match, and the loops will quickly locate the exact time if it is valid. If the input contains placeholders that could lead to invalid times (for example, "2?" for the hour where ? could be 4), the hour loop will skip those values because the regular expression will not match, thereby avoiding the generation of illegal times such as "24:00".

The method also gracefully handles inputs where the entire string consists of placeholders ("??:??"). In this scenario, the first iteration of the hour loop selects 23, and the first iteration of the minute loop selects 59, resulting in the maximum time "23:59".

Performance Optimizations

A notable optimization is the early pruning of hour candidates. By checking the hour part of the pattern before entering the minute loop, the algorithm eliminates the need to evaluate all 60 minute possibilities for hours that cannot possibly satisfy the pattern. This reduces the number of regular-expression evaluations dramatically in cases where the hour field is heavily constrained.

The descending order of iteration for both hours and minutes ensures that the first successful match is the optimal solution, allowing the method to exit immediately without exploring lower-valued candidates. This early exit strategy prevents unnecessary computation once the maximum time has been identified.

Formatting with f-strings (f"{hour:02d}" and f"{minute:02d}") is efficient and avoids the overhead of more verbose string manipulation methods. The use of a single compiled regular-expression pattern per call (the regex string) also minimizes the cost associated with pattern compilation, as the pattern is reused for each match operation within the loops.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a broken clock that has some missing numbers where question marks are. This path of code acts like a detective trying to figure out what time it should be. It first looks at all the possible hours starting from the very end of the day and working backward. It checks if the numbers it is testing match the spots where the question marks are. Once it finds an hour that fits perfectly, it does the exact same thing for the minutes. It tries every minute from fifty-nine all the way down to zero. As soon as it finds a combination of hours and minutes that matches the pattern, it stops and tells everyone what the final time is.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.48 | σ = 1.62

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
Krazune C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
Krazune C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
28 links | 17 authors | 8 languages

Videos

1 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

13 solutions   October 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality