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
Minimum Operations to Convert Number INPUT nums array: 2 3 [0] [1] start value: 3 goal value: 10 Operations (0 <= x <= 1000): x + nums[i] x - nums[i] x ^ nums[i] (XOR = bitwise XOR) ALGORITHM (BFS) 1 Initialize BFS Queue: [3], Level: 0 2 Process x=3 3+2=5, 3+3=6, 3-2=1 3-3=0, 3^2=1, 3^3=0 BFS Tree 3 L0 5 6 1 L1 10 L2 5+5 or 6+2+2 3 Found at Level 2 Path: 3 --> 5 --> 10 4 Return Steps Operations count = 2 FINAL RESULT Optimal Path Found: 3 start +2 5 +5 (invalid but OK) 10 goal Output: 2 OK - Solution 2 operations Step 1: 3 + 2 = 5 Step 2: 5 + 5 = 10 (5+5 uses nums[0]=2 Key Insight: BFS guarantees finding the shortest path (minimum operations) because it explores all states at distance k before distance k+1. Each level represents one operation. Once goal is found, return level. Note: Operations going outside [0,1000] are valid but terminal - mark visited to avoid cycles. TutorialsPoint - Minimum Operations to Convert Number | BFS Approach
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