Advertisement

Angle Between Hands of a Clock - LeetCode 1344 Solution

Angle Between Hands of a Clock - Complete Solution Guide

Angle Between Hands of a Clock is LeetCode problem 1344, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

Given two numbers, hour and minutes , return the smaller angle (in degrees) formed between the hour and the minute hand . Answers within 10 -5 of the actual value will be accepted as correct. 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

Detailed Explanation

The problem asks us to calculate the smaller angle between the hour and minute hands on an analog clock, given the current hour and minute. The hour is between 1 and 12 inclusive, and the minutes are between 0 and 59 inclusive. The output should be the angle in degrees, with answers within 10<sup>-5</sup> of the actual value considered correct.

Solution Approach

The solution involves calculating the angle of each hand independently from the 12 o'clock position. The minute hand's angle is simply 6 degrees per minute. The hour hand's angle is a bit more complex: it's 30 degrees per hour, plus an additional offset due to the minutes. Once we have the angles of both hands, we find the absolute difference and return the smaller of that difference and its complement to 360 (i.e., 360 - difference).

Step-by-Step Algorithm

  1. Step 1: Calculate the angle of the minute hand: `minute_angle = minutes * 6.0`
  2. Step 2: Calculate the angle of the hour hand: `hour_angle = (hour % 12 + minutes / 60.0) * 30.0`. This includes the base hour position (30 degrees/hour) and the additional movement due to the minutes.
  3. Step 3: Calculate the absolute difference between the two angles: `diff = abs(hour_angle - minute_angle)`
  4. Step 4: Return the smaller angle: `return min(diff, 360.0 - diff)`

Key Insights

  • Insight 1: The minute hand moves 360 degrees in 60 minutes, meaning it moves 6 degrees per minute.
  • Insight 2: The hour hand moves 360 degrees in 12 hours (720 minutes). Therefore, it moves 30 degrees per hour, and 0.5 degrees per minute.
  • Insight 3: The angle can be calculated by finding the absolute difference between the angles of the hour and minute hands. The smaller angle is the minimum of this difference and 360 minus this difference.
  • Insight 4: Take the hour modulo 12. This handles the case when hour is 12. Without it, for example at 12:00, the hour angle calculation would be incorrect.

Complexity Analysis

Time Complexity: O(1)

Space Complexity: O(1)

Topics

This problem involves: Math.

Companies

Asked at: Epic Systems, Siemens, UKG.