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 ZeroArray: [1,1,4,2,3], x = 511423RemoveKeepRemovex = 5 - 1 = 4x = 4 - 3 = 1After 2 operations: x = 5 - 1 - 3 = 1 ≠ 0Need to continue removing from ends until x = 0Output: 2 operations
Understanding the Visualization
1
Input
Array [1,1,4,2,3] and target x=5
2
Process
Remove elements from ends to reduce x to 0
3
Output
Minimum 2 operations needed
Key Takeaway
🎯 Key Insight: Transform the problem using complement thinking - find the longest middle subarray to keep instead of elements to remove from ends
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