Problem
You are given an integer array nums
consisting of 2 * n
integers.
You need to divide nums
into n
pairs such that:
- Each element belongs to exactly one pair.
- The elements present in a pair are equal.
Return true
if nums can be divided into n
pairs, otherwise return false
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
nums.length == 2 * n
1 <= n <= 500
1 <= nums[i] <= 500
Solution
Method 1 - Using frequency map
This problem can be solved using the concept of counting occurrences of elements in the array. The key points are:
- Since each pair comprises equal elements, the frequency of each element in the array must be even (because one pair requires 2 of the same element).
- If all elements in the array satisfy this condition, the array can be divided into
n
pairs; otherwise, it cannot.
The approach is as follows:
- Use a hash map (or dictionary in Python) to count occurrences of each element.
- Check if all counts are even.
- Return
true
if they are, otherwisefalse
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m)
, wherem
is the number of elements innums
.- Computing the frequency count takes
O(m)
-
- Checking the frequency counts takes
O(m)
(since unique elements are bounded bym
).
- Checking the frequency counts takes
- Computing the frequency count takes
- 🧺 Space complexity:
O(k)
, wherek
is the number of unique elements innums
for using hashmap.