#2224

Minimum Number of Operations to Convert Time

Easy
StringGreedyGreedyDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution focuses on minimizing the number of operations by always taking the largest possible step first. This greedy approach ensures that we reduce the difference to zero in the fewest moves.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert both current and correct times from 'HH:MM' format to total minutes since midnight.
  2. 2Step 2: Calculate the difference in minutes between correct and current.
  3. 3Step 3: Use a greedy approach to subtract the largest possible increments (60, 15, 5, 1) from the difference until it reaches zero, counting the number of operations.
solution.py18 lines
1# Full working Python code
2
3def minOperations(current: str, correct: str) -> int:
4    def to_minutes(time):
5        h, m = map(int, time.split(':'))
6        return h * 60 + m
7
8    current_minutes = to_minutes(current)
9    correct_minutes = to_minutes(correct)
10    diff = correct_minutes - current_minutes
11    operations = 0
12
13    for add in [60, 15, 5, 1]:
14        operations += diff // add
15        diff %= add
16
17    return operations
18

Complexity note: The complexity is O(1) because we only perform a fixed number of operations (4 possible increments) regardless of the input size.

  • 1Always prioritize larger increments to minimize the number of operations.
  • 2Converting time to a single unit (minutes) simplifies the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.