Magicsheet logo

Minimum Operations to Convert Number

Medium
25%
Updated 8/1/2025

Asked by 1 Company

Minimum Operations to Convert Number

1. What is this problem about?

You are given an initial number start and a target number goal. You also have an array of integers called nums. In one operation, you can take your current number x and perform either x + nums[i], x - nums[i], or x ^ nums[i] (XOR) using any number from the array. You want to find the minimum number of operations to reach the goal. However, if your current number x goes outside the range 0 to 1000, you cannot perform any more operations starting from that x (though that x might be the goal).

2. Why is this asked in interviews?

This "Minimum Operations to Convert Number interview question" is a classic Google-style shortest path problem. It tests a candidate's ability to apply Breadth-First Search (BFS) to a state-space search. It also checks if you can correctly handle constraints (the 0-1000 range) while still allowing the target to be any integer.

3. Algorithmic pattern used

The algorithmic pattern is Breadth-First Search (BFS). Since each operation has a cost of 1, BFS is guaranteed to find the shortest path to the goal. You use a queue to keep track of the current numbers and a visited array (size 1001) to ensure you don't process the same number multiple times, which prevents infinite loops and redundant work.

4. Example explanation

  • start: 1, goal: 3, nums: [1, 2]
  • From 1, possible operations:
    • 1 + 1 = 2
    • 1 + 2 = 3 (Goal reached! Operations: 1)
    • 1 - 1 = 0
    • 1 ^ 2 = 3 (Goal reached! Operations: 1) Minimum operations: 1.

5. Common mistakes candidates make

A common error is not correctly handling the goal when it's outside the 0-1000 range. While you can't continue from a number like 1050, you can still reach it. Another mistake is using a hash map for "visited" instead of a fixed-size boolean array, which is slower for small, fixed ranges. Failing to check if the goal is reached before checking the range constraint can also lead to incorrect results.

6. Interview preparation tip

When you see a "minimum steps to reach a target" problem with a limited number of possible states, BFS should be your first choice. Always define your "state" clearly—in this case, the state is simply the current value of the number.

Similar Questions