Divide Array Into Equal Pairs - Problem

You are given an integer array nums consisting of 2 * n integers.

Your task is 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.

Example: For array [3,2,3,2,2,2], we can form pairs (3,3), (2,2), and (2,2), so return true.

Input & Output

example_1.py โ€” Python
$ Input: nums = [3,2,3,2,2,2]
โ€บ Output: true
๐Ÿ’ก Note: We can form pairs: (3,3), (2,2), and (2,2). Each number appears an even number of times (3 appears 2 times, 2 appears 4 times).
example_2.py โ€” Python
$ Input: nums = [1,2,3,4]
โ€บ Output: false
๐Ÿ’ก Note: Each number appears exactly once (odd count), so no valid pairs can be formed. We need each number to appear an even number of times.
example_3.py โ€” Python
$ Input: nums = [1,1]
โ€บ Output: true
๐Ÿ’ก Note: Simple case with one pair (1,1). The number 1 appears 2 times (even count), so perfect pairing is possible.

Constraints

  • 2 โ‰ค nums.length โ‰ค 3 * 104
  • nums.length is even
  • 1 โ‰ค nums[i] โ‰ค 500
  • The array length is always 2 * n for some integer n

Visualization

Tap to expand
๐Ÿงฆ The Sock Pairing Problem ๐ŸงฆREDBLUEREDBLUEBLUEBLUECounting PhaseRED SocksCount: 2 โœ“BLUE SocksCount: 4 โœ“Pairing Resultโœ… SUCCESS: All socks paired perfectly!
Understanding the Visualization
1
Count Your Socks
Go through your laundry basket and count how many of each sock type you have
2
Check for Even Counts
Every sock type must appear an even number of times to form complete pairs
3
Determine Success
If any sock type has an odd count, you'll have unmatched socks - return false
Key Takeaway
๐ŸŽฏ Key Insight: Every number must appear an even number of times to form complete pairs - just like needing an even number of each sock type to avoid lonely socks!
Asked in
Amazon 12 Google 8 Microsoft 6 Meta 4
38.4K Views
Medium Frequency
~12 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