Learnitweb

LeetCode Problem 1344: Angle Between Hands of a Clock

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:

  1. The clock is a 360° circle.
  2. The minute hand moves:
    • 360° in 60 minutes → 6° per minute.
  3. The hour hand moves:
    • 360° in 12 hours → 30° per hour.
    • It also moves slightly every minute → 0.5° per minute.

Formula Derivation

  1. Minute hand angle = minutes * 6
  2. Hour hand angle = (hour % 12) * 30 + (minutes * 0.5)
    • (hour % 12) ensures that 12 o’clock is treated as 0 hour.
  3. Difference = |hour_angle - minute_angle|
  4. 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.

StepFormulaCalculationResult
Minute hand angleminutes * 615 * 690°
Hour hand angle(3 % 12) * 30 + (15 * 0.5)90 + 7.597.5°
Absolute difference97.5 – 90
Smaller anglemin(7.5, 360 – 7.5)min(7.5, 352.5)7.5°

Output: 7.5


Example 2: hour = 12, minutes = 30

StepFormulaCalculationResult
Minute hand angle30 * 6180°
Hour hand angle(12 % 12) * 30 + (30 * 0.5)0 + 1515°
Absolute difference180 – 15
Smaller anglemin(165, 195)165°

Output: 165


Example 3: hour = 9, minutes = 0

StepFormulaCalculationResult
Minute hand angle0 * 6
Hour hand angle(9 % 12) * 30 + (0 * 0.5)270 + 0270°
Absolute difference270 – 0
Smaller anglemin(270, 90)90°

Output: 90


Key Takeaways

  1. The minute hand moves 6° per minute.
  2. The hour hand moves 0.5° per minute.
  3. Always take the smaller angle between the two hands.
  4. Using modulo (hour % 12) ensures the formula works even for hour = 12.