Minimum Array Length After Pair Removals — LeetCode 2856 Python Solution
MediumGreedyArrayHash TableTwo PointersBinary SearchCounting
- Problem
- #2856
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
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
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 \times \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.