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 <= 120 <= minutes <= 59When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
We want to find the angle between the hour and minute hands on a clock. The brute force approach involves calculating the positions of the hands for every possible minute and hour combination and then finding the angle between them.
Here's how the algorithm would work step-by-step:
def angle_between_hands(hour, minute):
minute_degrees_per_minute = 6
hour_degrees_per_hour = 30
hour_degrees_per_minute = 0.5
minute_hand_position = minute * minute_degrees_per_minute
# Hour hand moves based on the current hour and minutes passed in that hour
hour_hand_position = (hour % 12) * hour_degrees_per_hour + \
minute * hour_degrees_per_minute
angle = abs(hour_hand_position - minute_hand_position)
# We need to return the smaller angle between the two hands
if angle > 180:
angle = 360 - angle
return angleThe goal is to calculate the angle between the hour and minute hands on a clock. We can do this efficiently by figuring out how far each hand is from the 12, and then finding the difference between those two positions.
Here's how the algorithm would work step-by-step:
def angle_between_hands(hour, minutes):
# Calculate minute hand angle.
minute_angle = minutes * 6
# Hour hand moves fractionally.
hour_angle = (hour % 12 + minutes / 60) * 30
# Find the difference.
angle_difference = abs(hour_angle - minute_angle)
# Get the smaller angle.
if angle_difference > 180:
angle_difference = 360 - angle_difference
return angle_difference| Case | How to Handle |
|---|---|
| Hour is negative | Return an error message or throw an exception, as hours cannot be negative. |
| Minute is negative | Return an error message or throw an exception, as minutes cannot be negative. |
| Hour is greater than 12 | Return an error message or throw an exception, as it is a 12-hour clock. |
| Minute is greater than 59 | Return an error message or throw an exception, as minutes cannot exceed 59. |
| Hour is 0 | Treat hour 0 as hour 12 when calculating the angle. |
| Minute is 0 | Calculate the hour hand position accurately when minutes are zero. |
| Hour is 12 and minute is 0 | The angle should be 0 as both hands point at the same position. |
| Floating point precision errors | Use Math.abs() to ensure a positive angle and handle potential inaccuracies when calculating the angle to determine the smaller one. |