Make Array Elements Equal to Zero - Problem

You are given an integer array nums. Start by selecting a starting position curr such that nums[curr] == 0, and choose a movement direction of either left or right.

After that, you repeat the following process:

  • If curr is out of the range [0, n - 1], this process ends.
  • If nums[curr] == 0, move in the current direction by incrementing curr if you are moving right, or decrementing curr if you are moving left.
  • Else if nums[curr] > 0: Decrement nums[curr] by 1. Reverse your movement direction (left becomes right and vice versa). Take a step in your new direction.

A selection of the initial position curr and movement direction is considered valid if every element in nums becomes 0 by the end of the process.

Return the number of possible valid selections.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,0,1,0,2]
Output: 2
💡 Note: Start at index 1 going right, or start at index 3 going left. Both configurations can make all elements zero through the bouncing process.
Example 2 — Single Zero
$ Input: nums = [1,0,2]
Output: 2
💡 Note: Can start at index 1 going either left or right. Both directions eventually make all elements zero.
Example 3 — No Valid Configurations
$ Input: nums = [1,2,3]
Output: 0
💡 Note: No zero positions exist, so no valid starting configurations are possible.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • 0 ≤ nums[i] ≤ 1000
  • At least one element in nums is 0

Visualization

Tap to expand
Make Array Elements Equal to Zero INPUT nums = [3, 0, 1, 0, 2] 3 i=0 0 i=1 1 i=2 0 i=3 2 i=4 Valid Starting Positions: Where nums[curr] == 0 1 Position index 1 3 Position index 3 Direction Options: Left or Right from each pos LEFT RIGHT ALGORITHM STEPS 1 Find Zero Positions Locate indices with 0 2 Calculate Prefix Sum Sum of elements to left 3 Calculate Suffix Sum Sum of elements to right 4 Compare Sums Valid if left == right Pos Left Right Valid? 1 3 3 OK 3 4 2 NO left==right or |diff|<=1 counts for 2 directions FINAL RESULT Valid Selections Found: 2 Valid Combinations: 1 Start at index 1 Go LEFT: left=3, right=3 2 Start at index 1 Go RIGHT: left=3, right=3 Output: 2 Key Insight: For a starting position to be valid, the sum of elements on the left must equal the sum on the right. Each bounce decrements one element, and direction reversal ensures balanced reduction. If sums are equal, BOTH directions work (count 2). If |leftSum - rightSum| == 1, ONE direction works (count 1). TutorialsPoint - Make Array Elements Equal to Zero | Mathematical Pattern Recognition
Asked in
Google 12 Amazon 8 Meta 5
12.5K Views
Medium Frequency
~15 min Avg. Time
234 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