The Clock Examiner
A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- medium
- Seniority
- L3
- Asked in
- phData
Problem
You're rendering an analog clock widget and need the angle between its two hands. Given hour (0-23) and minute (0-59), return the smaller angle in degrees between the hour and minute hands on a 12-hour dial, where the hour hand advances smoothly as the minutes pass rather than jumping on the hour.
Two hands on a clock: how wide is the gap?
Example 1
Input:
hour = 3, minute = 0
Output:
90
Example 2
Input:
hour = 12, minute = 30
Output:
165
Worked solution and explanation
What this really is
Strip the clock face away and this is two angular positions on a circle, then the shorter arc between them. The whole problem hinges on one detail almost everyone botches under pressure: the hour hand does not sit on the hour, it creeps forward as the minutes pass. Compute it as hour * 30 and you'll nail 3:00 but be off by 15 degrees at 12:30. The second trap is forgetting a clock is circular, so a raw difference of 240 is really a 120 degree gap.
Break down the requirements
Step 1: Place the hour hand, including its drift
Each hour is 30 degrees apart (360 / 12), and the hour hand drifts another 0.5 degrees for every minute past the hour. Position: (hour % 12) * 30 + minute * 0.5. The % 12 is what folds a 23-hour clock back onto the 12-hour face.
Step 2: Place the minute hand
The minute hand sweeps a full 360 degrees every 60 minutes, so 6 degrees per minute. Position: minute * 6.
Step 3: Reduce to the shorter arc
Take the absolute difference of the two positions, then fold it back across the circle with min(diff, 360 - diff). That guarantees you always report the smaller of the two arcs, never more than 180.
The solution
def clock_angle(hour: int, minute: int) -> float:
hour_pos = (hour % 12) * 30 + minute * 0.5
minute_pos = minute * 6
diff = abs(hour_pos - minute_pos)
return min(diff, 360 - diff)Common follow-up questions
- How many times per day do the hands overlap? (Tests combinatorial reasoning: the hands overlap 22 times in 24 hours, not 24.)
- What if you need to return the angle as an exact fraction to avoid floating point? (Tests knowledge of the `fractions.Fraction` module or manual integer math.)
- How would you find all times where the angle is exactly 90 degrees? (Tests solving the equation algebraically and enumerating solutions.)
- What edge case occurs at 12:00, and why does the modulo handle it? (Tests that `hour % 12` correctly maps 12 to 0.)