Interview Question Series | Season 3

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

  1. 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).

  2. 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

  1. Calculate the angle of the minute hand from 12:00 position.

  2. Calculate the angle of the hour hand from 12:00 position.

  3. Compute the absolute difference between these two angles.

  4. 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

  1. Minute Angle Calculation:

    • minutes * 6.0 converts minutes to degrees (since each minute is 6°).

  2. 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.

  3. 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)

  1. Minute angle: 15 * 6 = 90°

  2. Hour angle: (3 % 12)*30 + 15*0.5 = 90 + 7.5 = 97.5°

  3. Difference: |97.5 – 90| = 7.5°

  4. Complement: 360 – 7.5 = 352.5°

  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.

Scroll to Top