Make Array Zero by Subtracting Equal Amounts - Problem

You are given a non-negative integer array nums. In one operation, you must:

  • Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
  • Subtract x from every positive element in nums.

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,5,0,3,5]
Output: 3
💡 Note: Operation 1: x=1, subtract from all positives → [0,4,0,2,4]. Operation 2: x=2, subtract from all positives → [0,2,0,0,2]. Operation 3: x=2, subtract from all positives → [0,0,0,0,0]. Total: 3 operations.
Example 2 — With Zeros
$ Input: nums = [0]
Output: 0
💡 Note: Array already contains all zeros, so no operations needed.
Example 3 — All Same Values
$ Input: nums = [2,2,2,2]
Output: 1
💡 Note: All elements are the same non-zero value, so only one operation needed to make all zeros.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Make Array Zero by Subtracting Equal Amounts INPUT nums array: 1 idx 0 5 idx 1 0 idx 2 3 idx 3 5 idx 4 Unique non-zero values: 1 3 5 {1, 3, 5} = 3 unique values nums = [1,5,0,3,5] ALGORITHM STEPS 1 Create Set Store unique non-zero elements 2 Filter Zeros Skip 0 (already zero) 3 Count Unique Set size = operations needed 4 Return Size len(set) = answer Set Construction: set([1,5,0,3,5]) - {0} = {1, 3, 5} unique = set(nums) - {0} return len(unique) FINAL RESULT 3 Operations to reach all zeros: Op 1: x=1 (min non-zero) [1,5,0,3,5] --> [0,4,0,2,4] Op 2: x=2 (min non-zero) [0,4,0,2,4] --> [0,2,0,0,2] Op 3: x=2 (min non-zero) [0,2,0,0,2] --> [0,0,0,0,0] All elements are now 0! 0 0 0 0 0 Output: 3 Key Insight: Each unique non-zero value in the array requires exactly ONE operation to eliminate it. When we subtract the minimum non-zero value, we eliminate at least one unique value from the array. Therefore: minimum operations = count of unique non-zero elements = len(set(nums) - {0}) TutorialsPoint - Make Array Zero by Subtracting Equal Amounts | Set-Based Count Approach Time: O(n) | Space: O(n)
Asked in
Google 15 Meta 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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