Minimum Operations to Convert Number

medium array bfs

Problem

Start at integer start; in one operation pick x in nums and replace the current value y with y+x, y-x, or y XOR x. Values outside [0, 1000] are illegal. Return the fewest operations to reach goal, or -1.

Inputnums = [2, 4, 12], start = 2, goal = 12
Output2
2 → 14 (XOR 12) → 12 (subtract 2).

from collections import deque

def minimum_operations(nums, start, goal):
    seen = {start}
    q = deque([(start, 0)])
    while q:
        y, d = q.popleft()
        for x in nums:
            for ny in (y + x, y - x, y ^ x):
                if ny == goal:
                    return d + 1
                if 0 <= ny <= 1000 and ny not in seen:
                    seen.add(ny)
                    q.append((ny, d + 1))
    return -1
function minimumOperations(nums, start, goal) {
  const seen = new Set([start]);
  const q = [[start, 0]];
  while (q.length) {
    const [y, d] = q.shift();
    for (const x of nums) {
      for (const ny of [y + x, y - x, y ^ x]) {
        if (ny === goal) return d + 1;
        if (ny >= 0 && ny <= 1000 && !seen.has(ny)) {
          seen.add(ny);
          q.push([ny, d + 1]);
        }
      }
    }
  }
  return -1;
}
class Solution {
    public int minimumOperations(int[] nums, int start, int goal) {
        java.util.Set<Integer> seen = new java.util.HashSet<>();
        seen.add(start);
        java.util.Deque<int[]> q = new java.util.ArrayDeque<>();
        q.offer(new int[]{ start, 0 });
        while (!q.isEmpty()) {
            int[] cur = q.poll();
            int y = cur[0], d = cur[1];
            for (int x : nums) {
                int[] cands = { y + x, y - x, y ^ x };
                for (int ny : cands) {
                    if (ny == goal) return d + 1;
                    if (ny >= 0 && ny <= 1000 && seen.add(ny)) q.offer(new int[]{ ny, d + 1 });
                }
            }
        }
        return -1;
    }
}
int minimumOperations(vector<int>& nums, int start, int goal) {
    unordered_set<int> seen{ start };
    queue<pair<int, int>> q;
    q.push({ start, 0 });
    while (!q.empty()) {
        auto [y, d] = q.front(); q.pop();
        for (int x : nums) {
            for (int ny : { y + x, y - x, y ^ x }) {
                if (ny == goal) return d + 1;
                if (ny >= 0 && ny <= 1000 && !seen.count(ny)) {
                    seen.insert(ny);
                    q.push({ ny, d + 1 });
                }
            }
        }
    }
    return -1;
}
Time: O(V · |nums|) with V = 1001 Space: O(V)