Make Array Zero by Subtracting Equal Amounts - Problem

You are given a non-negative integer array nums. Your goal is to make all elements equal to zero by performing a series of special operations.

In each operation, you must:

  1. Choose a positive integer x where x โ‰ค smallest non-zero element in the array
  2. Subtract x from every positive element in the array

For example, if nums = [3, 1, 6], the smallest non-zero element is 1. You could choose x = 1 and subtract it from all positive elements: [3-1, 1-1, 6-1] = [2, 0, 5].

Return the minimum number of operations needed to make every element in nums equal to 0.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, 5, 0, 3, 5]
โ€บ Output: 3
๐Ÿ’ก Note: The unique non-zero values are {1, 5, 3}. Operation 1: subtract 1 โ†’ [0,4,0,2,4]. Operation 2: subtract 2 โ†’ [0,2,0,0,2]. Operation 3: subtract 2 โ†’ [0,0,0,0,0].
example_2.py โ€” All Zeros
$ Input: nums = [0]
โ€บ Output: 0
๐Ÿ’ก Note: The array already contains only zeros, so no operations are needed.
example_3.py โ€” All Same Values
$ Input: nums = [3, 3, 3, 3]
โ€บ Output: 1
๐Ÿ’ก Note: All non-zero elements have the same value (3), so only one operation is needed to make all elements zero.

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 0 โ‰ค nums[i] โ‰ค 100
  • Follow up: Can you solve this in O(n) time?

Visualization

Tap to expand
Water Container Visualization316Minimum water level = 1In each operation, drain up to the minimum levelDrain line
Understanding the Visualization
1
Initial State
Containers have water levels [3, 1, 6]. Lowest non-empty = 1
2
First Drain
Drain 1 unit from all โ†’ [2, 0, 5]. Container 2 is now empty
3
Second Drain
Drain 2 units from remaining โ†’ [0, 0, 3]. Container 1 is now empty
4
Final Drain
Drain 3 units from last container โ†’ [0, 0, 0]. All empty!
Key Takeaway
๐ŸŽฏ Key Insight: The number of operations equals the number of unique non-zero water levels, since each unique level requires exactly one draining operation to eliminate.
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
52.3K Views
Medium Frequency
~8 min Avg. Time
1.8K 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