1344. Angle Between Hands of a Clock
- Math
- Geometry
TIME
O(1)
SPACE
O(1)
Intuition
Each hand has a fixed angular speed, so we can compute the exact angle of each hand from the 12 o'clock position and take the difference. The only subtlety is that the hour hand also moves as the minutes pass, it is not fixed at the hour mark.
Approach
- The minute hand sweeps a full
360°in 60 minutes, so it sits at6 * minutesdegrees. - The hour hand sweeps
360°in 12 hours =30°per hour, plus0.5°per minute. Usinghour % 12(so12maps to0), it sits at30 * (hour % 12) + 0.5 * minutesdegrees. - Take the absolute difference of the two angles.
- The hands form two angles summing to
360°; return the smaller one:min(diff, 360 - diff).
Complexity
- Time: O(1)
- Space: O(1)
Edge Cases
hour = 12-> treat as0viahour % 12minutes = 0-> hour hand exactly on the hour mark- Difference exactly
180°-> bothdiffand360 - diffare180, returns180 - Hour hand past the mark (e.g. 3:30) -> the
0.5 * minutesterm accounts for it
Code
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
"""
1344. Angle Between Hands of a Clock
Time: O(1)
Space: O(1)
"""
minute_angle = 6 * minutes
hour_angle = 30 * (hour % 12) + 0.5 * minutes
diff = abs(hour_angle - minute_angle)
return min(diff, 360 - diff)/**
* 1344. Angle Between Hands of a Clock
* Time: O(1)
* Space: O(1)
*/
class Solution {
public double angleClock(int hour, int minutes) {
double minuteAngle = 6.0 * minutes;
double hourAngle = 30.0 * (hour % 12) + 0.5 * minutes;
double diff = Math.abs(hourAngle - minuteAngle);
return Math.min(diff, 360.0 - diff);
}
}