X of a Kind in a Deck of Cards
Problem statement
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:
- Each group has exactly
Xcards. - All the cards in each group have the same integer.
Example 1:
Input: deck = [1,2,3,4,4,3,2,1]Output: trueExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].
Example 2:
Input: deck = [1,1,1,2,2,2,3,3]Output: falseExplanation: No possible partition.
Constraints:
1 <= deck.length <= 1040 <= deck[i] < 104
My solution
/**
* @param {number[]} deck
* @return {boolean}
*/
var hasGroupsSizeX = function(deck) {
if (deck.length === 1) {
return false
}
const map = new Map();
for (const num of deck) {
if (!map.has(num)) {
map.set(num, 0)
}
map.set(num, map.get(num) + 1)
}
let minGroup;
// console.log(map)
for (const count of map.values()) {
// console.log(minGroup)
if (minGroup === undefined) {
minGroup = count;
} else {
minGroup = gcd(minGroup, count)
}
}
// console.log(minGroup)
if (minGroup < 2) {
return false
}
for (const count of map.values()) {
if (count % minGroup !== 0) {
return false
}
}
return true;
};
function lcm (a, b) {
let gcdValue = gcd(a, b);
return (a * b) / gcdValue;
}
function gcd(a, b) {
if (b === 0) {
return a
}
return gcd(b, a % b)
}