Skip to main content
Back to problems
#2059
Medium Algorithms

Minimum operations to convert number

Array Breadth-First Search
51.6% acceptance
Feb 25, 2026
680
34
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.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_operations(nums: Vec<i32>, start: i32, goal: i32) -> i32 {
    use std::collections::{VecDeque, HashSet};
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();
    queue.push_back((start, 0i32));
    visited.insert(start);

    while let Some((x, ops)) = queue.pop_front() {
      for &n in &nums {
        for next in [x + n, x - n, x ^ n] {
          if next == goal {
            return ops + 1;
          }
          if next >= 0 && next <= 1000 && !visited.contains(&next) {
            visited.insert(next);
            queue.push_back((next, ops + 1));
          }
        }
      }
    }
    -1
  }
}