Minimum Number of Operations to Convert Time

This problem involves converting one 24-hour time to another using the minimum number of operations. In one operation, you can increase the current time by 1, 5, 15, or 60 minutes. You are given two strings, current and correct, representing the starting and target times respectively. Your task is to figure out the minimum number of operations required to change current into correct.

Let’s break down the problem:

  1. Convert both current and correct from “HH:MM” format to total minutes past midnight. This makes the difference calculation straightforward.

  2. Calculate the difference in minutes between correct and current. This gives the total minutes we need to add to current to get correct.

  3. Determine how many operations we need to add the total minutes. We try to use as few operations as possible, so we start with the operation that adds the most minutes: 60 minutes. Count how many 60-minute operations we can perform, then do the same for 15-minute operations, 5-minute operations, and finally 1-minute operations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
    def convertTime(self, current: str, correct: str) -> int:
        # Function to convert "HH:MM" to total minutes
        def time_to_minutes(time):
            hours, minutes = map(int, time.split(":"))
            return hours * 60 + minutes

        # Convert both current and correct to total minutes
        current_minutes = time_to_minutes(current)
        correct_minutes = time_to_minutes(correct)

        # Calculate the difference in minutes
        diff = correct_minutes - current_minutes

        # Initialize the operation count
        operations = 0

        # Count the operations
        for minutes in [60, 15, 5, 1]:
            operations += diff // minutes
            diff %= minutes

        return operations

This code works by greedily using the operations that add the most minutes first. It has a time complexity of O(1), as the number of operations does not depend on the size of the input. The space complexity is also O(1), as we only use a fixed amount of space.