Minimum Operations to Reduce X to Zero - 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,4,2,3], x = 5
Output: 2
💡 Note: Remove nums[4]=3 and nums[0]=1 (or nums[1]=1), then x becomes 5-3-1=1, then remove nums[1]=1 (or nums[0]=1). Total 2 operations to make x=0.
Example 2 — Impossible Case
$ Input: nums = [3,2,20,1,1,3], x = 10
Output: 5
💡 Note: Remove from right: 3+1+1+3+2=10, so 5 operations needed.
Example 3 — Single Element
$ Input: nums = [5], x = 5
Output: 1
💡 Note: Remove the only element nums[0]=5 to make x=0. One operation needed.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 104
  • 1 ≤ x ≤ 109

Visualization

Tap to expand
Minimum Operations to Reduce X to Zero INPUT Array nums: 1 i=0 1 i=1 4 i=2 2 i=3 3 i=4 Target x: 5 Operations allowed: - Remove leftmost element - Remove rightmost element - Subtract from x Total sum = 1+1+4+2+3 = 11 Need subarray sum = 11-5 = 6 ALGORITHM STEPS 1 Transform Problem Find longest subarray with sum = total - x = 6 2 Sliding Window Use two pointers to find max length subarray = target 3 Find Subarray Subarray [4,2] has sum=6 Length = 2 (indices 2-3) 1 1 4 2 3 Keep middle (green) = sum 6 4 Calculate Result ops = n - maxLen ops = 5 - 3 = 2 Remove: [1,1] from left OR [2,3] from right = x FINAL RESULT Optimal removal strategy: Option 1: Remove from right 1 1 4 2 3 Remove 3, then 2: 3+2 = 5 = x Option 2: Remove from both 1 1 4 2 3 Remove 1,1 left + 3 right: 1+1+3=5 (This takes 3 ops - not optimal) Minimum Operations: 2 OK - Solution Found! Key Insight: Instead of tracking removed elements (prefix + suffix), find the LONGEST middle subarray with sum = totalSum - x. The answer is n - maxLength. This transforms a two-pointer problem into a simpler sliding window problem. Time: O(n), Space: O(1). TutorialsPoint - Minimum Operations to Reduce X to Zero | Optimal Sliding Window Approach
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
124.5K Views
High Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen