Make Array Zero by Subtracting Equal Amounts — LeetCode 2357 Python Solution

EasyGreedyArrayHash TableSortingSimulationHeap (Priority Queue)
Problem
#2357
Reading time
2 min

The 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.

Example

Input
nums = [1,5,0,3,5]
Output
3
Explanation
In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].

Python solution

Python
class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        return len({x for x in nums if x})

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the array \textit{nums} auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2357. Make Array Zero by Subtracting Equal Amounts is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2357. Make Array Zero by Subtracting Equal Amounts?
LeetCode 2357. Make Array Zero by Subtracting Equal Amounts is rated Easy on LeetCode.
What is the time complexity of LeetCode 2357. Make Array Zero by Subtracting Equal Amounts?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2357. Make Array Zero by Subtracting Equal Amounts?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
What topics does LeetCode 2357. Make Array Zero by Subtracting Equal Amounts cover?
LeetCode 2357. Make Array Zero by Subtracting Equal Amounts is tagged Greedy, Array, Hash Table, Sorting, Simulation and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview