Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 17, 2025 20:09
Show Gist options
  • Save tatsuyax25/5253304a0833cca0349c8e4df2ba9ecc to your computer and use it in GitHub Desktop.
Save tatsuyax25/5253304a0833cca0349c8e4df2ba9ecc to your computer and use it in GitHub Desktop.
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, o
/**
* @param {number[]} nums
* @return {boolean}
*/
var divideArray = function(nums) {
// Create a map to store the frequency of each number
let frequencyMap = new Map();
let length = nums.length;
// Populate the frequency map
for (let i = 0; i < length; i++) {
frequencyMap.set(nums[i], (frequencyMap.get(nums[i]) || 0) + 1);
}
// Check if all frequencies are even
for (const count of frequencyMap.values()) {
if (count % 2 !== 0) {
// If any frequency is odd, return false
return false;
}
}
// If all frequencies are even, return true
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment