We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Number of Operations to Convert Time

Difficulty: Easy


Problem Description

You are given two strings current and correct representing two 24-hour times. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You need to return the minimum number of operations needed to convert current to correct.


Key Insights

  • The difference in minutes between current and correct determines the number of operations needed.
  • We can utilize a greedy approach by prioritizing larger increments (60, 15, 5, 1) to minimize the number of operations.
  • The constraints ensure that current is always less than or equal to correct, simplifying the calculation of the difference.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

To solve the problem, we first convert the current and correct time strings into total minutes since midnight. The difference in minutes between correct and current gives us the total number of minutes we need to increase. We then use a greedy approach to minimize the number of operations by taking the largest possible increments first (60, 15, 5, and then 1 minute).


Code Solutions

def convertTime(current: str, correct: str) -> int:
    # Convert the current and correct times to total minutes
    current_minutes = int(current[:2]) * 60 + int(current[3:])
    correct_minutes = int(correct[:2]) * 60 + int(correct[3:])
    
    # Find the difference in minutes
    diff = correct_minutes - current_minutes
    
    # Initialize the number of operations
    operations = 0
    
    # Use the largest increments first
    for increment in [60, 15, 5, 1]:
        operations += diff // increment  # Count how many of this increment we can use
        diff %= increment  # Reduce the difference accordingly
    
    return operations
← Back to All Questions