Divide Array Into Equal Pairs - 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,3,2,2,2]
Output: true
💡 Note: We can pair the elements as (3,3), (2,2), and (2,2). Each pair contains equal elements.
Example 2 — Impossible Pairing
$ Input: nums = [1,2,3,4]
Output: false
💡 Note: All elements are different, so no equal pairs can be formed.
Example 3 — Odd Frequency
$ Input: nums = [1,1,2,2]
Output: true
💡 Note: Element 1 appears 2 times (even) and element 2 appears 2 times (even). We can form pairs (1,1) and (2,2).

Constraints

  • 1 ≤ nums.length ≤ 100
  • nums.length is even
  • -100 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Divide Array Into Equal Pairs INPUT nums array (2n = 6 elements) 3 2 3 2 2 2 [0] [1] [2] [3] [4] [5] Goal: Divide into n = 3 equal pairs nums = [3,2,3,2,2,2] n = 3 pairs needed ALGORITHM STEPS 1 Count Frequency Use HashMap to count each element Val Count 3 2 2 4 2 Check Even Counts Each count must be divisible by 2 3 Verify All Elements 3: count=2, 2%2=0 OK 2: count=4, 4%2=0 OK 4 Return Result All even --> true Any odd --> false FINAL RESULT Valid Pairs Found: Pair 1 3 3 = Pair 2 2 2 = Pair 3 2 2 = Output: true All pairs valid! 3 pairs created from 6 elements (n=3) OK - Valid Division Key Insight: For an array to be divisible into equal pairs, every element must appear an even number of times. If any element has an odd frequency, we cannot pair all occurrences of that element. Time: O(n) | Space: O(n) for frequency map TutorialsPoint - Divide Array Into Equal Pairs | Optimal Solution (Hash Map Frequency Count)
Asked in
Google 15 Microsoft 12 Amazon 8
23.6K Views
Medium Frequency
~10 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen