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

Number: 2345

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given two 24-hour formatted time strings, current and correct, determine the minimum number of operations required to convert current to correct. In one operation, you can add 1, 5, 15, or 60 minutes to the current time. The task is to compute the minimum operations necessary to achieve the target time.


Key Insights

  • Convert both current and correct times to the total minutes since 00:00.
  • Compute the difference in minutes between correct and current.
  • Use a greedy approach by subtracting the largest possible operation interval (60 minutes first, then 15, then 5, and finally 1) until the difference is reduced to 0.
  • The greedy strategy works here as the operations are multiples that combine perfectly to form any minute difference.

Space and Time Complexity

Time Complexity: O(1) – Because the algorithm performs a fixed number of arithmetic operations regardless of input size.
Space Complexity: O(1) – Only a few variables are used for calculation.


Solution

The solution follows these steps:

  1. Parse the current and correct time strings into hours and minutes.
  2. Convert each time into total minutes from 00:00.
  3. Calculate the difference in minutes between correct and current.
  4. Use the largest operations first (60, then 15, then 5, then 1) to reduce the difference, incrementing an operation count each time.
  5. Return the total count of operations.

We utilize basic arithmetic operations and a greedy algorithm. This approach is efficient due to the small, constant number of operations required.


Code Solutions

# Convert time string to total minutes from 00:00
def convert_to_minutes(time_str):
    hours, minutes = map(int, time_str.split(':'))
    return hours * 60 + minutes

def min_operations(current, correct):
    # Calculate difference in minutes
    current_minutes = convert_to_minutes(current)
    correct_minutes = convert_to_minutes(correct)
    diff = correct_minutes - current_minutes
    
    operations = 0
    # List of operation steps available in descending order
    steps = [60, 15, 5, 1]
    
    # Greedily subtract the largest possible operation until diff is 0
    for step in steps:
        operations += diff // step  # Count how many steps can be applied
        diff %= step               # Reduce the difference
        
    return operations

# Example usage:
# print(min_operations("02:30", "04:35"))
← Back to All Questions