Problem Statement
Given two integers hour and minutes, return the smaller angle (in degrees) between the hour hand and the minute hand of a clock.
Example 1:
Input: hour = 12, minutes = 30 Output: 165
Example 2:
Input: hour = 3, minutes = 30 Output: 75
Example 3:
Input: hour = 3, minutes = 15 Output: 7.5
Constraints:
- 1 ≤ hour ≤ 12
- 0 ≤ minutes ≤ 59
- Answers must be within [0, 180].
Intuition
A clock has two hands — hour and minute — each rotating at different speeds.
We must find the smaller angle between them at a given time.
Key Observations:
- The clock is a 360° circle.
- The minute hand moves:
- 360° in 60 minutes → 6° per minute.
- The hour hand moves:
- 360° in 12 hours → 30° per hour.
- It also moves slightly every minute → 0.5° per minute.
Formula Derivation
- Minute hand angle =
minutes * 6 - Hour hand angle =
(hour % 12) * 30 + (minutes * 0.5)(hour % 12)ensures that 12 o’clock is treated as 0 hour.
- Difference =
|hour_angle - minute_angle| - Smaller angle =
Math.min(diff, 360 - diff)
Java Solution
public class Solution {
public double angleClock(int hour, int minutes) {
double minuteAngle = minutes * 6;
double hourAngle = (hour % 12) * 30 + (minutes * 0.5);
double diff = Math.abs(hourAngle - minuteAngle);
return Math.min(diff, 360 - diff);
}
}
Complexity Analysis
- Time Complexity: O(1)
All operations are constant-time arithmetic. - Space Complexity: O(1)
No extra space used.
Dry Run
Let’s dry run with hour = 3, minutes = 15.
| Step | Formula | Calculation | Result |
|---|---|---|---|
| Minute hand angle | minutes * 6 | 15 * 6 | 90° |
| Hour hand angle | (3 % 12) * 30 + (15 * 0.5) | 90 + 7.5 | 97.5° |
| Absolute difference | 97.5 – 90 | ||
| Smaller angle | min(7.5, 360 – 7.5) | min(7.5, 352.5) | 7.5° |
Output: 7.5
Example 2: hour = 12, minutes = 30
| Step | Formula | Calculation | Result |
|---|---|---|---|
| Minute hand angle | 30 * 6 | 180° | |
| Hour hand angle | (12 % 12) * 30 + (30 * 0.5) | 0 + 15 | 15° |
| Absolute difference | 180 – 15 | ||
| Smaller angle | min(165, 195) | 165° |
Output: 165
Example 3: hour = 9, minutes = 0
| Step | Formula | Calculation | Result |
|---|---|---|---|
| Minute hand angle | 0 * 6 | 0° | |
| Hour hand angle | (9 % 12) * 30 + (0 * 0.5) | 270 + 0 | 270° |
| Absolute difference | 270 – 0 | ||
| Smaller angle | min(270, 90) | 90° |
Output: 90
Key Takeaways
- The minute hand moves 6° per minute.
- The hour hand moves 0.5° per minute.
- Always take the smaller angle between the two hands.
- Using modulo (
hour % 12) ensures the formula works even forhour = 12.
