Problem 1344

Abstract / Summary

Find the smaller angle between the hour and minute hands of a clock at a given time.

Note

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

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
12 lines | 295 bytes | submitted October 29, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (200k+ submissions).

Typical patterns to solve this problem:
  • Math
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 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 fraction m becomes 0, and the hour fraction h reduces to hour / 12. The subsequent normalization yields an angle of 0 when the hour hand aligns with the minute hand (e.g., 12:00).

  • Midnight or noon representation (hour = 12). The division hour / 12 yields 1, which is equivalent to 0 on the unit circle. The wrap-around logic (if angle < 0: angle += 1) and the complement step ensure the correct result of 0 degrees for 12:00.

  • Times where the minute hand leads the hour hand (e.g., 3:45). The initial subtraction produces a negative angle; the addition of 1 converts it to the correct clockwise distance before the complement check.

  • Times producing exactly half-circle separation (angle == 0.5). The condition if angle > 0.5 excludes equality, leaving angle unchanged at 0.5, which correctly translates to 180 degrees.

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 sin or cos, which would introduce additional computational overhead.

  • Early normalization: The two conditional adjustments (angle < 0 and angle > 0.5) reduce the range of angle before 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.58 | σ = 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 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++
27 links | 16 authors | 7 languages

Videos

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

Solved On The Same Day

6 solutions   October 29, 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