Leetcode 2206. Divide Array Into Equal Pairs
LeetCode Problem 2206: Divide Array Into Equal Pairs
You are given an integer array nums
consisting of 2 * n
integers. You need to divide nums
into n
pairs such that each pair contains exactly two equal elements. Return true
if you can divide the array into n
pairs, otherwise return false
.
Input: nums = [3,2,3,2,2,2]
Output: true
Explanation:
There are 3 pairs such as (3, 3), (2, 2), (2, 2).
Input: nums = [1,2,3,4]
Output: false
Explanation:
There is no way to divide the array into pairs.
nums
is empty or has just one element?
nums
contains 2 * n
elements, so these cases should not occur.nums
or the values within nums
?
nums
.true
if all values have even frequencies, otherwise return false
.Here’s the implementation in C++:
#include <vector>
#include <unordered_map>
class Solution {
public:
bool divideArray(std::vector<int>& nums) {
std::unordered_map<int, int> freq;
// Count frequencies of each number
for (int num : nums) {
freq[num]++;
}
// Check if all frequencies are even
for (auto& entry : freq) {
if (entry.second % 2 != 0) {
return false;
}
}
return true;
}
};
O(n)
O(n)
time where n
is the number of elements in nums
.O(m)
time where m
is the number of distinct elements. In the worst case, m
can be n
, so this process is O(n)
.O(m)
m
distinct elements, which in the worst case could be n
. Hence, the space complexity is O(n)
.This solution efficiently checks if it’s possible to divide the array into equal pairs of elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?