Grouping elements by checking the Greatest Common Divisor (GCD) of their frequencies.
The original problem is here.
Card A and 6 copies of Card B. Can we partition them into identical groups of the same size $X$? collections.Counter in Python) to build out our frequency table. This completes our grouping volume awareness in $O(n)$ linear time.math.gcd sequentially traversing over the values map array using functools.reduce.True.import collections
from math import gcd
from functools import reduce
class Solution:
def hasGroupsSizeX(self, deck: list[int]) -> bool:
# 1. Count frequencies of each integer card via Hash Map
count = collections.Counter(deck)
# 2 & 3. Iteratively compute the GCD tracing through the entire frequency array
# reduce() continuously applies the gcd to rolling pair-wise values
overall_gcd = reduce(gcd, count.values())
# 4. Validate the partitioning bounds
return overall_gcd >= 2
class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
if len(deck) == 1:
return False
count = {}
for num in deck:
count[num] = count.get(num, 0) + 1
min_count = len(deck)+1
for num in count:
if count[num] < min_count:
min_count = count[num]
result = 0
for j in range(2, min_count+1):
if (min_count % j == 0):
if sum(((count[i] % j) > 0) for i in count) == 0:
return True
return False