LeetCode 1658, Medium. Topics: Array, Hash Table, Binary Search, Sliding Window, Prefix Sum. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 20 parametrized pytest cases, and a playground notebook:
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
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, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026