Minimum Number of Operations to Convert Time — LeetCode 2224 Python Solution

EasyGreedyString
Problem
#2224
Pattern
Greedy
Reading time
2 min

The 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.

Example

Input
current = "02:30", correct = "04:35"
Output
3
Explanation
We can convert current to correct in 3 operations as follows:

Python solution

Python
class Solution:
    def convertTime(self, current: str, correct: str) -> int:
        a = int(current[:2]) * 60 + int(current[3:])
        b = int(correct[:2]) * 60 + int(correct[3:])
        ans, d = 0, b - a
        for i in [60, 15, 5, 1]:
            ans += d // i
            d %= i
        return ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2224. Minimum Number of Operations to Convert Time is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2224. Minimum Number of Operations to Convert Time?
LeetCode 2224. Minimum Number of Operations to Convert Time is rated Easy on LeetCode.
What topics does LeetCode 2224. Minimum Number of Operations to Convert Time cover?
LeetCode 2224. Minimum Number of Operations to Convert Time is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview