You are given an integer array nums consisting of 2 * n integers.
You need to divide nums into n pairs such that:
Return true if nums can be divided into n pairs, otherwise return false.
Example 1:
Input: nums = [3,2,3,2,2,2]
Output: trueExplanation: There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.
If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.
Example 2:
Input: nums = [1,2,3,4]
Output: falseExplanation: There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.
Constraints:
nums.length == n1 <= n <= 5001 <= nums[i] <= 500Before attempting this problem, you should be comfortable with:
For an array to be divisible into pairs of equal elements, every distinct value must appear an even number of times. By sorting the array, identical elements become adjacent. We can then scan through and count consecutive runs of equal values. If any run has an odd length, we cannot form valid pairs.
false.true.We can count the frequency of each element using a hash map. After counting, we check if every element appears an even number of times. If any element has an odd count, it cannot be fully paired, so we return false.
false.true.Instead of counting all frequencies, we can use a set to track elements with odd occurrences. When we see an element, if it is already in the set (meaning we have seen it an odd number of times), we remove it. If it is not in the set, we add it. At the end, if the set is empty, all elements appeared an even number of times.
true if the set is empty, false otherwise.A common mistake is trying to actually form pairs and check if adjacent elements match after sorting. The problem only requires checking if each element appears an even number of times, not that the pairs are adjacent.
# Wrong: Checking adjacent pairs after sorting
nums.sort()
for i in range(0, len(nums), 2):
if nums[i] != nums[i + 1]: # IndexError if odd length
return False
# Correct: Just check if each count is even
for cnt in count.values():
if cnt % 2 == 1:
return FalseThe problem guarantees that nums has 2n elements. Some solutions add unnecessary checks for odd-length arrays or forget that the total count of elements is always even, which simplifies the problem to just checking individual element frequencies.
Sign in to join the discussion