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.

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

Input & Output

Example 1 — Basic Case
$ Input: current = "02:30", correct = "03:00"
Output: 2
💡 Note: Need 30 minutes difference. Use 2 operations of 15 minutes each: 02:30 → 02:45 → 03:00
Example 2 — Mixed Operations
$ Input: current = "11:00", correct = "11:01"
Output: 1
💡 Note: Need 1 minute difference. Use 1 operation of 1 minute: 11:00 → 11:01
Example 3 — Next Day Edge Case
$ Input: current = "23:59", correct = "00:00"
Output: 1
💡 Note: Need 1 minute to go from 23:59 to 00:00 (next day). Use 1 operation of 1 minute.

Constraints

  • current and correct are valid 24-hour times
  • current ≠ correct is not guaranteed (can be equal)

Visualization

Tap to expand
Minimum Operations to Convert Time INPUT 02:30 current 03:00 correct Time Difference 03:00 - 02:30 = 30 minutes Operations Available +60 +15 +5 +1 (minutes) ALGORITHM STEPS 1 Calculate Difference diff = 30 minutes 2 Try +60 min 30/60 = 0 ops, remain 30 3 Try +15 min 30/15 = 2 ops, remain 0 4 Done! diff = 0, stop Greedy Process 30 min +15 15 min 15 min +15 0 min FINAL RESULT Output 2 Operations Used +15 02:30 --> 02:45 +15 02:45 --> 03:00 OK - Minimum Ops! 2 operations total 02:30 03:00 Key Insight: Greedy approach works because larger operations (60, 15, 5, 1) are multiples of smaller ones. Always use the largest operation possible first to minimize total operations. This guarantees optimal solution. Time Complexity: O(1) | Space Complexity: O(1) TutorialsPoint - Minimum Number of Operations to Convert Time | Greedy Approach
Asked in
Amazon 15 Microsoft 12
28.5K 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