MediumNo. 2856

Minimum Array Length After Pair Removals — LeetCode 2856 Python Solution

Topics
Greedy, Array, Hash Table, Two Pointers, Binary Search, Counting
Reading time
3 min

The problem

Given an integer array num sorted in non-decreasing order. You can perform the following operation any number of times: Choose two indices, i and j, where nums[i] < nums[j].

Python solution

PythonSolution
class Solution:
    def minLengthAfterRemovals(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        pq = [-x for x in cnt.values()]
        heapify(pq)
        ans = len(nums)
        while len(pq) > 1:
            x, y = -heappop(pq), -heappop(pq)
            x -= 1
            y -= 1
            if x > 0:
                heappush(pq, -x)
            if y > 0:
                heappush(pq, -y)
            ans -= 2
        return ans

Complexity

Time
O(n × log n)
Space · auxiliary
O(n)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2856. Minimum Array Length After Pair Removals is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
1782Count Pairs Of NodesHard
0349Intersection of Two ArraysEasy
0350Intersection of Two Arrays IIEasy
0532K-diff Pairs in an ArrayMedium
0621Task SchedulerMedium
09233Sum With MultiplicityMedium

Frequently asked questions

How hard is LeetCode 2856. Minimum Array Length After Pair Removals?

LeetCode 2856. Minimum Array Length After Pair Removals is rated Medium on LeetCode.

What is the time complexity of LeetCode 2856. Minimum Array Length After Pair Removals?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 2856. Minimum Array Length After Pair Removals?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2856. Minimum Array Length After Pair Removals cover?

LeetCode 2856. Minimum Array Length After Pair Removals is tagged Greedy, Array, Hash Table, Two Pointers, Binary Search 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.

Free to download. Check it runs on your machine, then pick a plan.