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:

1
2
3
4
5
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:

1
2
3
4
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 * 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:

  1. Use a hash map (or dictionary in Python) to count occurrences of each element.
  2. Check if all counts are even.
  3. Return true if they are, otherwise false.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
    }
}
1
2
3
4
5
6
7
8
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), where m is the number of elements in nums.
    • Computing the frequency count takes O(m)
      • Checking the frequency counts takes O(m) (since unique elements are bounded by m).
  • 🧺 Space complexity: O(k) ,  where k is the number of unique elements in nums for using hashmap.