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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code