Compute clock hand angle with seconds and milliseconds
Scale AISoftware Engineer · Technical ScreenLast updated
This question evaluates understanding of angular geometry and numeric precision in time-based systems, testing competency in parsing varying time formats and computing continuous clock-hand positions; it is in the Coding & Algorithms domain and requires both conceptual understanding of angular motion and practical application in precise computation. Interviewers commonly ask this problem to assess an applicant's ability to model continuous motion, handle 12/24-hour representations and edge cases, and manage seconds- and milliseconds-level precision when deriving and implementing numerical formulas.
You are given a time in the format "HH:MM", representing a 24-hour clock time with hours and minutes. Extend this to potentially include seconds and milliseconds as follow-ups.
- Base problem
Given a string
timein the format"HH:MM", where:
0 <= HH <= 230 <= MM <= 59
Compute the smallest positive angle (in degrees) between the hour hand and the minute hand on an analog clock that shows this time. The result can be a floating point number.
- Follow-up 1: Add seconds
Now suppose the input is
"HH:MM:SS", with:
0 <= SS <= 59
Recompute the smallest angle between the hour and minute hands, taking seconds into account (the hour and minute hands move continuously, not in discrete jumps).
- Follow-up 2: Add milliseconds
Now suppose the input is
"HH:MM:SS.mmm", with:
0 <= mmm <= 999
Recompute the smallest angle between the hour and minute hands, taking seconds and milliseconds into account.
Specify the formulas you would use for the hand positions, how you handle 24-hour times on a 12-hour clock face, and then implement a function that returns the minimal angle between the two hands as a floating point value.
Input: a time string in one of the above formats. Output: the smallest angle between the hour and minute hands, in degrees (a floating point number).
Describe the algorithm and then implement it in your preferred programming language.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.