Minimum Number of Operations to Make Array Empty — LeetCode 2870 Python Solution

MediumGreedyArrayHash TableCounting
Problem
#2870
Pattern
Greedy
Reading time
2 min

The problem

You are given a 0-indexed array nums consisting of positive integers. There are two types of operations that you can apply on the array any number of times: Choose two elements with equal values and delete them from the array.

Example

Input
nums = [2,3,3,2,2,4,2,3,4]
Output
4
Explanation
We can apply the following operations to make the array empty:

Python solution

Python
class Solution:
    def minOperations(self, nums: List[int]) -> int:
        count = Counter(nums)
        ans = 0
        for c in count.values():
            if c == 1:
                return -1
            ans += (c + 2) // 3
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2870. Minimum Number of Operations to Make Array Empty is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2870. Minimum Number of Operations to Make Array Empty?
LeetCode 2870. Minimum Number of Operations to Make Array Empty is rated Medium on LeetCode.
What is the time complexity of LeetCode 2870. Minimum Number of Operations to Make Array Empty?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2870. Minimum Number of Operations to Make Array Empty?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2870. Minimum Number of Operations to Make Array Empty cover?
LeetCode 2870. Minimum Number of Operations to Make Array Empty is tagged Greedy, Array, Hash Table and Counting 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