Minimum Operations to Convert Number - Problem

You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal.

You can perform the following operation repeatedly on the number x:

If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:

  • x + nums[i]
  • x - nums[i]
  • x ^ nums[i] (bitwise-XOR)

Note that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.

Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.

Input & Output

Example 1 — Basic Transformation
$ Input: nums = [2,3], start = 3, goal = 10
Output: 2
💡 Note: We can transform 3 → 5 (3+2) → 10 (5+3+2). Total 2 operations needed.
Example 2 — XOR Operation
$ Input: nums = [3,5,1,4,2], start = 0, goal = 11
Output: 3
💡 Note: Transform 0 → 3 (0^3) → 7 (3^4) → 11 (7^4). Using XOR operations efficiently.
Example 3 — Impossible Case
$ Input: nums = [2,4,6], start = 1, goal = 8
Output: -1
💡 Note: Cannot reach 8 from 1 using only even numbers within the valid range 0-1000.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000
  • 0 ≤ start, goal ≤ 1000
  • All the integers in nums are distinct

Visualization

Tap to expand
Number Transformation: Convert Start to Goalnums = [2,3]Operations Array3start10goalTransformAvailable Operationsx + nums[i]x - nums[i]x ^ nums[i]AdditionSubtractionXORValid only if 0 ≤ result ≤ 10005Step 1: 3 + 2 = 510Step 2: 5 + 2 + 3 = 10Answer: 2
Understanding the Visualization
1
Input
Array nums, start value, and goal value
2
Transform
Use +, -, ^ operations with array elements
3
Result
Minimum operations to reach goal or -1 if impossible
Key Takeaway
🎯 Key Insight: Use BFS to explore all possible transformations level by level, guaranteeing the shortest path to the goal
Asked in
Google 28 Facebook 15 Amazon 12
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen