Python 1344.py
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
m = minutes / 60
h = hour / 12 + m / 12
angle = h - m
if angle < 0:
angle += 1
if angle > 0.5:
angle = 1 - angle
return 360 * angle
Difficulty
and has an acceptance rate of about 64% (200k+ submissions).
Typical patterns to solve this problem:
- Math
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 implementation calculates the smallest angle, in degrees, between the hour and minute hands of an analog clock for a given time expressed by hour and minutes. The algorithm works entirely with fractional representations of the clock face, avoiding any trigonometric functions, and returns a floating-point result.
Conversion of Minutes to Fractional Position
The first arithmetic operation transforms the minute value into a fraction of a full rotation.
m = minutes / 60
Here m represents the position of the minute hand as a value between 0 (pointing at 12) and just under 1 (one full circle). This fractional approach simplifies later calculations because the clock can be treated as a unit circle.
Determination of Hour Hand Position Including Minute Offset
The hour hand does not jump discretely each hour; it moves continuously as minutes pass. The code captures this by adding a minute-derived offset to the hour fraction.
h = hour / 12 + m / 12
hour / 12 yields the base hour position as a fraction of the circle, while m / 12 adds the incremental movement caused by the minutes. The result h is also a value in the range [0, 1) after normalization.
Raw Angular Difference
The raw difference between the two hand positions is computed as a simple subtraction.
angle = h - m
At this stage angle may be negative (if the minute hand is ahead of the hour hand) or greater than 0.5 (indicating that the larger of the two possible angles has been measured).
Normalization to Positive Fraction
If the raw difference is negative, the algorithm wraps it around the clock face by adding a full rotation.
if angle < 0:
angle += 1
This step guarantees that angle lies in the interval [0, 1), representing a clockwise distance from the minute hand to the hour hand.
Selection of the Smaller Angle
A clock yields two possible angles between the hands: the clockwise distance and its complement. The code selects the smaller of the two by checking whether the current fraction exceeds half a circle.
if angle > 0.5:
angle = 1 - angle
When angle is greater than 0.5, its complement 1 - angle corresponds to the counter-clockwise distance, which is the minimal angle. After this conditional, angle is guaranteed to be in the range [0, 0.5].
Conversion to Degrees
Finally, the fractional angle is scaled to degrees by multiplying by the total number of degrees in a circle.
return 360 * angle
The returned value is a floating-point number representing the smallest angle between the hour and minute hands for the supplied time.
Edge Cases Handled
The algorithm gracefully manages several boundary conditions without additional branching:
-
Exact hour marks (
minutes = 0). The minute fractionmbecomes0, and the hour fractionhreduces tohour / 12. The subsequent normalization yields an angle of0when the hour hand aligns with the minute hand (e.g.,12:00). -
Midnight or noon representation (
hour = 12). The divisionhour / 12yields1, which is equivalent to0on the unit circle. The wrap-around logic (if angle < 0: angle += 1) and the complement step ensure the correct result of0degrees for12:00. -
Times where the minute hand leads the hour hand (e.g.,
3:45). The initial subtraction produces a negativeangle; the addition of1converts it to the correct clockwise distance before the complement check. -
Times producing exactly half-circle separation (
angle == 0.5). The conditionif angle > 0.5excludes equality, leavingangleunchanged at0.5, which correctly translates to180degrees.
Performance Optimizations Observed
The implementation is deliberately concise, executing a fixed sequence of arithmetic operations:
-
Constant-time execution: No loops or recursion are present; the method completes in a deterministic number of steps regardless of input values.
-
Avoidance of heavy math functions: By representing positions as fractions of a circle, the code sidesteps trigonometric calculations such as
sinorcos, which would introduce additional computational overhead. -
Early normalization: The two conditional adjustments (
angle < 0andangle > 0.5) reduce the range ofanglebefore the final multiplication, ensuring that the multiplication operates on a bounded value and minimizing the risk of floating-point inaccuracies. -
Minimal variable usage: Only three intermediate variables (
m,h,angle) are allocated, keeping memory footprint low and improving cache locality.
Overall, the method delivers the required result with a lean computational profile, making it well-suited for high-frequency calls or inclusion in performance-critical contexts.
ELI5 - Simplified Explanation
Imagine a big round clock on the wall with numbers from one to twelve. The long hand points to the minutes and moves all the way around the circle every hour. The short hand points to the hour and moves just a little bit every time the long hand travels.
To find the space between the two hands, the code first turns the time into a tiny fraction of the whole circle. The minute hand has a position, and the hour hand has a position that depends on both the hour and how far the minute hand has traveled.
Next, the math subtracts one hand from the other to see how far apart they are. Because the clock is a circle, if the gap is negative, the code adds a full circle to make it positive again. If the gap is too large, it means the hands are measuring the long way around, so it flips the math to find the shorter, friendlier path. Finally, that small slice of the circle is multiplied by three hundred and sixty, which is the total number of degrees in a full trip around the clock face, telling exactly how wide the space between the two hands 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 | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1227: Airplane Seat Assignment Probability
- problem 1315: Sum of Nodes with Even-Valued Grandparent
- problem 1325: Delete Leaves With a Given Value
- problem 1333: Filter Restaurants by Vegan-Friendly, Price and Distance
- problem 1220: Count Vowels Permutation
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