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
def angleClock(hour: int, minutes: int) -> float:
"""Calculates the smaller angle between the hour and minute hands on a clock.
Args:
hour: The hour (1-12).
minutes: The minutes (0-59).
Returns:
The smaller angle in degrees between the hour and minute hands.
"""
# Calculate the angle of the hour hand
hour_angle = (hour % 12 + minutes / 60) * 30
# Calculate the angle of the minute hand
minute_angle = minutes * 6
# Calculate the absolute difference between the angles
angle_diff = abs(hour_angle - minute_angle)
# Return the smaller angle
return min(angle_diff, 360 - angle_diff)
# Example usage:
# print(angleClock(12, 30))
# print(angleClock(3, 30))
# print(angleClock(3, 15))
The most straightforward way to solve this problem is to directly calculate the angles of the hour and minute hands and then find the difference. This involves:
The provided Python code implements the optimal solution, which is essentially a refined version of the naive approach. Here's a breakdown:
(hour % 12 + minutes / 60) * 30
accurately calculates the hour hand's angle.minutes * 6
calculates the minute hand's angle.abs(hour_angle - minute_angle)
.angle_diff
and 360 - angle_diff
, ensuring the smallest angle between the hands is returned.The run-time complexity of the angleClock
function is O(1) because it involves only a few arithmetic operations that take constant time regardless of the input values. Specifically:
hour_angle
involves a fixed number of arithmetic operations.minute_angle
involves a single multiplication.angle_diff
involves a subtraction and an absolute value operation.Since all these operations take constant time, the overall run-time complexity is O(1).
The space complexity of the angleClock
function is O(1) because it uses a fixed amount of memory regardless of the input values. Specifically:
hour_angle
, minute_angle
, angle_diff
) are used to store intermediate results, but the number of variables does not depend on the input.Since the memory usage remains constant, the space complexity is O(1).
% 12
ensures that when the hour is 12, it is treated as 0 for angle calculation purposes, which is correct.abs()
function ensures that the angle difference is always positive, simplifying the logic for finding the smaller angle.This approach effectively handles all valid inputs within the constraints specified by the problem statement.