#2059

Minimum Operations to Convert Number

Medium
ArrayBreadth-First SearchBreadth-First SearchGraph Traversal
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

Using a breadth-first search (BFS) approach allows us to explore the shortest path to the goal efficiently. We can track visited states to avoid redundant calculations and ensure we find the minimum operations needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a queue and add the starting value x (start) along with the operation count (0).
  2. 2Step 2: While the queue is not empty, dequeue an element and check if it equals the goal.
  3. 3Step 3: If it does, return the operation count. If not, apply all operations (+, -, ^) for each number in nums and enqueue the new values with incremented operation count.
  4. 4Step 4: Use a set to track visited values to prevent cycles and redundant processing.
solution.py15 lines
1from collections import deque
2
3def minOperations(nums, start, goal):
4    queue = deque([(start, 0)])
5    visited = set([start])
6    while queue:
7        x, ops = queue.popleft()
8        if x == goal:
9            return ops
10        for num in nums:
11            for next_x in (x + num, x - num, x ^ num):
12                if next_x not in visited:
13                    visited.add(next_x)
14                    queue.append((next_x, ops + 1))
15    return -1

Complexity note: The complexity is linear because we are processing each number in nums and each state only once due to the visited set.

  • 1Using BFS ensures we explore the shortest path to the goal efficiently.
  • 2Tracking visited states prevents cycles and redundant processing.

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