Skip to main content
Back to problems
#1658
Medium Algorithms

Minimum operations to reduce x to zero

Array Hash Table Binary Search Sliding Window Prefix Sum
40.4% acceptance
Feb 25, 2026
5754
127
You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Return the minimum number of operations to reduce x to exactly 0 if possible, otherwise, return -1.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 {
    let total: i32 = nums.iter().sum();
    let target = total - x;
    if target < 0 {
      return -1;
    }
    if target == 0 {
      return nums.len() as i32;
    }
    // Find max-length subarray with sum == target (sliding window)
    let n = nums.len();
    let mut max_len = -1i32;
    let mut window_sum = 0i32;
    let mut left = 0;
    for right in 0..n {
      window_sum += nums[right];
      while window_sum > target && left <= right {
        window_sum -= nums[left];
        left += 1;
      }
      if window_sum == target {
        max_len = max_len.max((right - left + 1) as i32);
      }
    }
    if max_len == -1 {
      -1
    } else {
      n as i32 - max_len
    }
  }
}