LeetCode 1344 – Angle Between Hands of a Clock – Detailed Solution
Problem Understanding
We need to calculate the smallest angle between the hour and minute hands of a 12-hour clock given the current time in hours and minutes.
Key Insights
-
Minute Hand Movement:
-
The minute hand completes a full 360° circle in 60 minutes.
-
Therefore, each minute corresponds to 6° (360° / 60 = 6° per minute).
-
-
Hour Hand Movement:
-
The hour hand completes a full 360° circle in 12 hours.
-
Therefore, each hour corresponds to 30° (360° / 12 = 30° per hour).
-
Additionally, the hour hand moves as minutes pass – it moves 0.5° per minute (30° per hour / 60 minutes = 0.5° per minute).
-
Approach
-
Calculate the angle of the minute hand from 12:00 position.
-
Calculate the angle of the hour hand from 12:00 position.
-
Compute the absolute difference between these two angles.
-
Return the smaller angle between the calculated difference and its complement to 360° (since a circle is 360°, the smaller angle between θ and 360°-θ is the correct answer).
Solution Code
class Solution {
public:
double myMin(double a, double b) {
return (a < b) ? a : b;
}
double myAbs(double a) {
return (a < 0) ? -a : a;
}
double angleClock(int hour, int minutes) {
double minute_angle = minutes * 6.0;
double hour_angle = (hour % 12) * 30.0 + minutes * 0.5;
double angle = myAbs(hour_angle - minute_angle);
return myMin(angle, 360.0 - angle);
}
};
Explanation
-
Minute Angle Calculation:
-
minutes * 6.0
converts minutes to degrees (since each minute is 6°).
-
-
Hour Angle Calculation:
-
hour % 12
handles the 12-hour format (12 becomes 0). -
Multiply by 30.0 to get the base hour angle.
-
Add
minutes * 0.5
to account for the hour hand’s movement during the minutes.
-
-
Angle Difference:
-
The absolute difference between the two angles gives one possible angle.
-
The complement (360° – difference) gives the other possible angle.
-
We return the smaller of these two angles.
-
Example Walkthrough (hour = 3, minutes = 15)
-
Minute angle: 15 * 6 = 90°
-
Hour angle: (3 % 12)*30 + 15*0.5 = 90 + 7.5 = 97.5°
-
Difference: |97.5 – 90| = 7.5°
-
Complement: 360 – 7.5 = 352.5°
-
Result: min(7.5, 352.5) = 7.5°
Time and Space Complexity
-
Time Complexity: O(1) – All operations are constant time calculations.
-
Space Complexity: O(1) – Only a few variables are used regardless of input size.