Minimum Number of Operations to Convert Time - Problem

You are given two strings current and correct representing two 24-hour times.

24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.

In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.

Goal: Return the minimum number of operations needed to convert current to correct.

Example: If current is "02:30" and correct is "04:35", you need to add 125 minutes total. The optimal way is: 2 operations of 60 minutes + 1 operation of 5 minutes = 3 operations.

Input & Output

example_1.py โ€” Basic Example
$ Input: current = "02:30", correct = "04:35"
โ€บ Output: 3
๐Ÿ’ก Note: We need to add 125 minutes total. Optimal: 2ร—60 + 1ร—5 = 125 minutes in 3 operations.
example_2.py โ€” No Operations Needed
$ Input: current = "11:00", correct = "11:01"
โ€บ Output: 1
๐Ÿ’ก Note: Only 1 minute difference, so we need exactly 1 operation of +1 minute.
example_3.py โ€” Multiple Denominations
$ Input: current = "00:00", correct = "23:59"
โ€บ Output: 32
๐Ÿ’ก Note: 1439 minutes total. Optimal: 23ร—60 + 3ร—15 + 4ร—1 = 1380+45+4 = 1439 minutes in 30 operations.

Constraints

  • current and correct are in the format "HH:MM"
  • current <= correct
  • HH is between 00 and 23
  • MM is between 00 and 59
  • Time difference is at most 23:59 (1439 minutes)

Visualization

Tap to expand
Time Conversion = Coin Change ProblemFrom: 02:30150 minutesStarting timeTo: 04:35275 minutesTarget timeDifference125 minutesAmount to addGreedy Coin Selection (Use Largest First):60minUse 2 times125 รท 60 = 2 R 515minUse 0 times5 รท 15 = 0 R 55minUse 1 time5 รท 5 = 1 R 01minUse 0 times0 remainingTotal Operations2 + 0 + 1 + 0 = 3
Understanding the Visualization
1
Calculate Total Amount
Find the time difference in minutes (like calculating total change needed)
2
Use Largest Denomination
Use as many 60-minute operations as possible (like using $60 bills first)
3
Handle Remainder
Use 15-minute, then 5-minute, then 1-minute operations for the remainder
4
Count Total Operations
Sum up all operations used (like counting total bills given)
Key Takeaway
๐ŸŽฏ Key Insight: This greedy approach works perfectly because 60, 15, 5, and 1 form a 'canonical coin system' where using the largest denomination first always leads to the optimal solution - just like making change with standard currency!
Asked in
Amazon 25 Google 18 Microsoft 12 Meta 8
24.8K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen