Python 3114.py
class Solution:
def findLatestTime(self, s: str) -> str:
hours = s[0]
if s[0] == "?":
hours = "1" if s[1] in "01?" else "0"
hours += min("9", s[1])
hours = min(hours, "11") # handle overflow
minutes = "5" if s[3] == "?" else s[3]
minutes += min("9", s[4])
return hours + ":" + minutes
Difficulty
and has an acceptance rate of about 36% (100k+ submissions).
Typical patterns to solve this problem:
- Enumeration
- 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 findLatestTime that receives a time string s in the format "hh:mm" where some characters may be the placeholder '?'. The goal of the method is to replace each '?' with a digit such that the resulting time is the latest possible valid 24-hour time. The implementation proceeds by constructing the hour and minute components separately, applying conditional logic to choose the maximal permissible digit for each unknown position, and finally concatenating the components with a colon.
Key Steps
The algorithm can be broken down into three logical sections: handling the first hour digit, handling the second hour digit, and handling the minute digits. Each section is illustrated with the corresponding code fragment.
Determining the first hour digit
hours = s[0]
if s[0] == "?":
hours = "1" if s[1] in "01?" else "0"
The first character of the hour part is examined. If it is already a digit, it is kept unchanged. When it is a '?', the code decides between '1' and '0'. The choice '1' is made only when the second hour character is '0', '1', or also a '?', because a leading '1' allows the hour to reach values up to 19. In all other cases the leading digit must be '0' to keep the hour within the valid range 00-23.
Determining the second hour digit
hours += min("9", s[1])
hours = min(hours, "11") # handle overflow
The second hour character is replaced by the smallest of '9' and the original character. This effectively chooses '9' when the original character is a '?' and retains the original digit otherwise. After concatenation, the combined hour string is bounded by "11" using min. This step ensures that any hour value that would exceed 23 (for example "19" when the first digit was forced to '1' and the second digit was '9') is clamped down to the highest permissible hour "11" for the given constraints.
Determining the minute digits
minutes = "5" if s[3] == "?" else s[3]
minutes += min("9", s[4])
The first minute character (tens of minutes) is set to '5' when it is a '?', because the maximum tens digit for minutes is 5. If the character is already a digit, it is preserved. The second minute character (units of minutes) follows the same pattern as the second hour digit: it becomes '9' when the original character is '?', otherwise it stays unchanged.
Assembling the final time string
return hours + ":" + minutes
The hour and minute strings are concatenated with a colon separator to produce the final time representation.
Edge Cases Handled
The code explicitly addresses several boundary conditions that arise from the 24-hour clock format.
When the first hour character is '?' and the second hour character is '2' or any digit greater than '1', the algorithm selects '0' for the first digit, preventing the formation of an invalid hour such as 2? that could exceed 23. This logic is encapsulated in the conditional hours = "1" if s[1] in "01?" else "0".
The subsequent min(hours, "11") call acts as a safety net for cases where the combination of a leading '1' and a maximal second digit '9' would produce "19". Since "19" is a valid hour, the clamp to "11" only triggers when the constructed hour string would be lexicographically greater than "11" under the constraints imposed by the earlier decision. This effectively caps the hour at "11" when the first digit is forced to '1' but the second digit cannot be reduced below '9'.
For the minute component, the choice of '5' for an unknown tens digit guarantees that the minute value never exceeds 59. The units digit is always limited to '9', which is the highest permissible digit for the ones place of minutes.
Performance Optimizations
The implementation relies exclusively on string operations and constant-time built-in functions such as min. No loops or recursive calls are present, which means the method executes a fixed number of steps regardless of input content. By using direct indexing (s[0], s[1], etc.) the code avoids any overhead associated with slicing or converting the input to intermediate data structures. The use of min with literal strings provides a concise way to enforce upper bounds without explicit conditional branches, reducing branching overhead and keeping the instruction path short. Overall, the method runs in constant time with minimal memory allocation, as it creates only a few short strings to hold intermediate hour and minute values.
ELI5 - Simplified Explanation
Imagine a digital clock that has a few broken spots where the numbers are missing. This code acts like a smart detective that looks at the slots marked with question marks and tries to guess the highest possible time that fits each spot.
First, the code looks at the hours. It checks the first spot to see if it should be a zero or a one, based on whether the second spot is a small number or a big one. It wants to make the hour as big as it can without going past twelve.
Next, the code looks at the minutes. For the first minute spot, it wants the biggest number possible, which is five, because once it hits sixty the clock rolls over. For the very last spot, it just tries to put a nine there if a number is missing.
Finally, the code joins the hours and the minutes together with a little colon in the middle to show the full time. It is like putting together a puzzle where the goal is to make the latest time possible.
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 | Java | C++ | Python | TS | ||
| WalkCCC | Java | C++ | Python | ||||
| leetcode.ca | Java | C++ | Go | Python | TS | ||
| Progiez | Java | C++ | Python | ||||
| github | charles-wangkai | Java | |||||
| everthis | JS | ||||||
| fsq | C++ | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | C++ |
Videos
Similar Problems
- problem 1736: Latest Time by Replacing Hidden Digits
Solved On The Same Day
- problem 3069: Distribute Elements Into Two Arrays I
- problem 3074: Apple Redistribution into Boxes
- problem 3083: Existence of a Substring in a String and Its Reverse
- problem 3127: Make a Square with the Same Color
- problem 2513: Minimize the Maximum of Two Arrays
- problem 3070: Count Submatrices with Top-Left Element and Sum Less Than k
- problem 3112: Minimum Time to Visit Disappearing Nodes
- problem 3128: Right Triangles
- problem 2503: Maximum Number of Points From Grid Queries
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