#2998
Minimum Number of Operations to Make X and Y Equal
MediumDynamic ProgrammingBreadth-First SearchMemoizationBreadth-First SearchDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a breadth-first search (BFS) but with a more targeted approach. We only explore valid operations and track the minimum steps needed to reach y from x efficiently.
⚙️
Algorithm
3 steps- 1Step 1: If y >= x, return y - x directly since we can only increment x.
- 2Step 2: Initialize a queue for BFS starting from x and a set to track visited nodes.
- 3Step 3: For each number dequeued, apply valid operations and enqueue new states until y is reached.
solution.py27 lines
1from collections import deque
2
3def min_operations(x, y):
4 if y >= x:
5 return y - x
6 queue = deque([(x, 0)]) # (current value, steps)
7 visited = set([x])
8 while queue:
9 current, steps = queue.popleft()
10 if current == y:
11 return steps
12 # Possible operations
13 for next_val in [current - 1, current + 1]:
14 if next_val not in visited:
15 visited.add(next_val)
16 queue.append((next_val, steps + 1))
17 if current % 5 == 0:
18 next_val = current // 5
19 if next_val not in visited:
20 visited.add(next_val)
21 queue.append((next_val, steps + 1))
22 if current % 11 == 0:
23 next_val = current // 11
24 if next_val not in visited:
25 visited.add(next_val)
26 queue.append((next_val, steps + 1))
27 return -1ℹ
Complexity note: The time complexity is O(n) because we are exploring each state at most once, and the space complexity is O(n) due to the queue and visited set.
- 1When y >= x, the quickest way to reach y is to increment x directly.
- 2The operations of dividing by 5 or 11 can significantly reduce x, making them powerful tools for large reductions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.