Maximum Number of Pairs in Array — LeetCode 2341 Python Solution

EasyArrayHash TableCounting
Problem
#2341
Pattern
Hash Map
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. In one operation, you may do the following: Choose two integers in nums that are equal.

Example

Input
nums = [1,3,2,1,3,2,2]
Output
[3,1]
Explanation
Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].

Python solution

Python
class Solution:
    def numberOfPairs(self, nums: List[int]) -> List[int]:
        cnt = Counter(nums)
        s = sum(v // 2 for v in cnt.values())
        return [s, len(nums) - s * 2]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(C) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2341. Maximum Number of Pairs in Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2341. Maximum Number of Pairs in Array?
LeetCode 2341. Maximum Number of Pairs in Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 2341. Maximum Number of Pairs in Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2341. Maximum Number of Pairs in Array?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 2341. Maximum Number of Pairs in Array cover?
LeetCode 2341. Maximum Number of Pairs in Array is tagged 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