Hands Apart
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- phData
Problem
A calendar widget renders an analog clock face and needs to know how far apart the two hands sit. Given a hour (1 to 12) and a minute (0 to 59), return the smaller of the two angles in degrees between the hour and minute hands, remembering that the hour hand drifts continuously toward the next mark as the minutes pass rather than jumping on the hour.
Two hands. One gap. One number.
Example 1
Input:
hour = 3, minute = 0
Output:
90
Example 2
Input:
hour = 3, minute = 30
Output:
75
Worked solution and explanation
What this is really testing
Strip the clock face away and this is a question about whether you believe the hour hand actually moves. Almost everyone nails 3:00 equals 90 degrees, writes hour * 30, and ships it. The candidates who pass remember that by 3:30 the hour hand has already crept a quarter of the way toward 4, so the gap is 75 degrees, not 90. Get that one detail wrong and every non-zero minute is off by up to 15 degrees, with passing visible tests hiding the bug.
Break down the requirements
Step 1: Place the minute hand
Sixty minutes cover the whole face, so each minute is 6 degrees: minute * 6.
Step 2: Place the hour hand
Each hour mark is 30 degrees apart, and the hand drifts 0.5 degrees for every minute past the hour: (hour % 12) * 30 + minute * 0.5. The % 12 is what keeps 12 o'clock at 0 rather than 360.
Step 3: Fold to the smaller arc
Take the absolute difference, then return min(diff, 360 - diff). The face is circular, so the two hands always carve out two arcs that sum to 360; you want the smaller one.
The solution
def clock_angle(hour: int, minute: int) -> float:
minute_angle = minute * 6
hour_angle = (hour % 12) * 30 + minute * 0.5
diff = abs(hour_angle - minute_angle)
return min(diff, 360 - diff)Common follow-up questions
- What if the input uses 24-hour format? (Tests whether you apply `% 12` correctly for values like 13 or 23.)
- At what times are the hands exactly opposite, at 180 degrees? (Tests reverse-engineering the formula to solve for minute given a target angle.)
- How would you handle seconds for sub-degree precision? (Tests extending the formula: seconds add 0.1 degrees to the minute hand and about 0.0083 to the hour hand.)