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
Difficulty
and has an acceptance rate of about 44% (100k+ submissions).
Typical patterns to solve this problem:
- Greedy
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Similar Problems
- problem 2437: Number of Valid Clock Times
- problem 3114: Latest Time You Can Obtain After Replacing Characters
Solved On The Same Day
- problem 1013: Partition Array Into Three Parts With Equal Sum
- problem 1668: Maximum Repeating Substring
- problem 1784: Check if Binary String Has at Most One Segment of Ones
- problem 2099: Find Subsequence of Length K With the Largest Sum
- problem 2383: Minimum Hours of Training to Win a Competition
- problem 2511: Maximum Enemy Forts That Can Be Captured
- problem 2739: Total Distance Traveled
- problem 331: Verify Preorder Serialization of a Binary Tree
- problem 400: Nth Digit
- problem 447: Number of Boomerangs
- problem 1476: Subrectangle Queries
- problem 1828: Queries on Number of Points Inside a Circle
Extra
- 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