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 determine if it is possible to divide this array into n
pairs such that for each pair (a, b)
, a == b
.
Return true
if it is possible to divide the array into n
pairs, otherwise return false
.
Example:
Input: nums = [3,2,3,2,2,2]
Output: true
Explanation:
There are 6 numbers and they can be divided into 3 pairs: (3, 3), (2, 2), (2, 2).
[-2^31, 2^31 - 1]
.true
or false
to indicate if it is possible to divide the array into pairs.To determine if it is possible to divide the array into pairs where each pair consists of identical numbers, we can follow these steps:
Here’s the Java code implementing the above strategy:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public boolean divideArray(int[] nums) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
// Count the frequency of each number in the array
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
// Check if all counts are even
for (int count : frequencyMap.values()) {
if (count % 2 != 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {3, 2, 3, 2, 2, 2};
System.out.println(solution.divideArray(nums)); // Output: true
}
}
m
is the number of unique elements in the array. In the worst case, m
can be equal to n
, making this step also O(n).This approach ensures that we efficiently determine if the array can be divided into pairs with equal values.
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?