Minimum Operations to Convert All Elements to Zero - Problem

You are given an array nums of size n, consisting of non-negative integers. Your task is to apply some (possibly zero) operations on the array so that all elements become 0.

In one operation, you can select a subarray [i, j] (where 0 <= i <= j < n) and set all occurrences of the minimum non-negative integer in that subarray to 0.

Return the minimum number of operations required to make all elements in the array 0.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,4]
Output: 7
💡 Note: Using the greedy approach: Position 0 (value 2) needs 1 operation. Position 1 (value 1) needs 1 operation (pops 2 from stack). Position 2 (value 3) needs 2 operations. Position 3 (value 4) needs 3 operations. Total: 1+1+2+3 = 7 operations.
Example 2 — All Same Elements
$ Input: nums = [3,3,3]
Output: 3
💡 Note: Each element requires exactly 1 operation since they're all the same value. Total: 3 operations.
Example 3 — Already Zero
$ Input: nums = [0,0,0]
Output: 0
💡 Note: All elements are already zero, so no operations are needed.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Operations to Convert All Elements to Zero INPUT Array nums: 2 i=0 1 i=1 3 i=2 4 i=3 nums = [2, 1, 3, 4] n = 4 elements All non-negative integers Goal: Convert all elements to 0 using minimum operations 0 0 0 0 ALGORITHM STEPS 1 Init Monotonic Stack Push 0 as base, count ops=0 2 Process Each Element Iterate through array left to right 3 Pop Greater Elements Pop while stack.top > current Each pop = 1 operation 4 Push if New Value Push current if != stack.top Monotonic Stack Trace: [0] --> push 2 --> [0,2] [0,2] --> pop 2(op+1) [0] --> push 1 --> [0,1] [0,1] --> push 3 --> [0,1,3] [0,1,3] --> pop 3(op+1) push 4, final pop all FINAL RESULT Operations Breakdown: Op 1: Set min=1 in [0,3] Op 2: Set min=2 in [0,0] Op 3: Set min=3 in [2,2] Op 4: Set min=4 in [3,3] Op 5: Final cleanup Total: 5 operations Output: 5 Final Array State: 0 0 0 0 OK - All zeros! Key Insight: The monotonic stack maintains elements in increasing order. When we encounter a smaller element, all larger elements on the stack must be zeroed out first (each pop = 1 operation). The number of operations equals the count of distinct non-zero values that need separate elimination steps. TutorialsPoint - Minimum Operations to Convert All Elements to Zero | Monotonic Stack Approach Time Complexity: O(n) | Space Complexity: O(n)
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~25 min Avg. Time
847 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