> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Minimum Operations to Reduce X to Zero

> Tested Python solution for LeetCode 1658 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 1658, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Binary Search](/catalog/topics/binary-search), [Sliding Window](/catalog/topics/sliding-window), [Prefix Sum](/catalog/topics/prefix-sum). [View on LeetCode](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1658   # by problem number
lcpy gen -s minimum_operations_to_reduce_x_to_zero   # by problem name
```

## Problem

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`. Note that this **modifies** the array for future operations.

Return the **minimum number** of operations to reduce `x` to **exactly** `0` if it is possible, otherwise, return `-1`.

### Examples

```
Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
```

```
Input: nums = [5,6,7,8,9], x = 4
Output: -1
```

```
Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
```

### Constraints

* 1 \<= nums.length \<= 10\<sup>5\</sup>
* 1 \<= nums\[i] \<= 10\<sup>4\</sup>
* 1 \<= x \<= 10\<sup>9\</sup>

**Follow up:** Can you solve it in `O(n)` time complexity?

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_operations_to_reduce_x_to_zero/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_operations_to_reduce_x_to_zero/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def min_operations(self, nums: list[int], x: int) -> int:
        total = sum(nums)
        target = total - x
        n = len(nums)
        if target == 0:
            return n
        if target < 0:
            return -1
        best = -1
        first_at = {0: -1}
        prefix = 0
        for i, val in enumerate(nums):
            prefix += val
            j = first_at.get(prefix - target)
            if j is not None and i - j > best:
                best = i - j
            if prefix not in first_at:
                first_at[prefix] = i
        return n - best if best != -1 else -1
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.