Maximum Number of Pairs in Array Problem
#2341
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2341.
You are given a 0-indexed integer array nums. In one operation, you may do the following:
- Choose two integers in
numsthat are equal. - Remove both integers from
nums, forming a pair.
The operation is done on nums as many times as possible.
Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.
Example 1:
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].
Form a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].
Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].
No more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.
Example 2:
Input: nums = [1,1]
Output: [1,0]
Explanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].
No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.
Example 3:
Input: nums = [0]
Output: [0,1]
Explanation: No pairs can be formed, and there is 1 number leftover in nums.
Constraints:
1 <= nums.length <= 1000 <= nums[i] <= 100
Solution
Approach: Counting
Count how many times each value appears. A value that appears v times gives v / 2 pairs (rounded down), and the pairs of all values add up to s. Each pair uses two elements, so the number of leftovers is n - 2 * s. The answer is [s, n - 2 * s].
Complexity: Time O(n), space O(C) where C = 101 is the range of values.
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]