KatInterview

Calculate Minimal Clock Hand Separation Angle

Math & Bit ManipulationAuto-graded · 26 test cases
MediumAuto-gradedMath & Bit Manipulationmathstringsgeometry

Last updated

Parse 24-hour timestamp strings (including optional seconds and milliseconds) and calculate the minor angle between analog clock hands.

Given a timestamp string representing a time on a 24-hour clock, determine the smallest non-negative angle (in degrees) between the hour hand and minute hand on a standard 12-hour analog clock.

The input time string will be formatted in one of three ways:

  • "HH:MM"
  • "HH:MM:SS"
  • "HH:MM:SS.mmm"

Where:

  • HH is an integer hours value in [0, 23].
  • MM is an integer minutes value in [0, 59].
  • SS is an integer seconds value in [0, 59].
  • mmm is an integer milliseconds value in [0, 999].

Both hands move continuously and smoothly as time passes:

  • The minute hand completes a full $360^\circ$ revolution every 60 minutes ($6^\circ$ per minute).
  • The hour hand completes a full $360^\circ$ revolution every 12 hours ($30^\circ$ per hour, or $0.5^\circ$ per minute).
  • Seconds and milliseconds advance both hands accordingly.

Return the smaller of the two angles formed between the two hands as a floating-point value (a number in the range $[0.0, 180.0]$).

Constraints

  • time matches one of the valid string formats described above.
  • Hours, minutes, seconds, and milliseconds are within their standard non-negative ranges.

Examples

Example 1

Input: clock_hand_angle('00:00')

Output: 0

Example 2

Input: clock_hand_angle('03:00')

Output: 90

Example 3

Input: clock_hand_angle('12:30')

Output: 165

Example 4

Input: clock_hand_angle('23:59:59')

Output: 0.09166666666664014

Example 5

Input: clock_hand_angle('23:59:59.999')

Output: 0.00009166666660576084

Hints

Hint 1

Convert the 24-hour format into a 12-hour analog dial by taking `hours % 12`.

Hint 2

Express the elapsed time into total sub-units (e.g., total fractional minutes or total milliseconds) to easily calculate absolute hand angles relative to the 12 o'clock position.

Hint 3

The hour hand moves at $30^\circ / 3600000$ degrees per millisecond, while the minute hand moves at $6^\circ / 60000$ degrees per millisecond. Find the absolute angle difference and return `min(diff, 360 - diff)`.