Divide Array Into Equal Pairs
EasyUpdated: Aug 2, 2025
Practice on:
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:
Input: nums = [3,2,3,2,2,2]
Output: true
Explanation:
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: false
Explanation:
There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.
Constraints:
nums.length == 2 * n1 <= n <= 5001 <= 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
npairs; 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
trueif they are, otherwisefalse.
Code
Java
class Solution {
public boolean divideArray(int[] nums) {
Map<Integer, Integer> freq = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
boolean ans = true;
for (int count : freq.values()) {
if (count % 2 != 0) {
ans = false;
break;
}
}
return ans;
}
}
Python
class Solution:
def divideArray(self, nums: List[int]) -> bool:
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
ans = all(count % 2 == 0 for count in freq.values())
return ans
Complexity
- ⏰ Time complexity:
O(m), wheremis 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), wherekis the number of unique elements innumsfor using hashmap.