~/problems / Number theory / Primes, divisors and GCD

Split a deck into equal groups

easy ~10 min

Each card in a deck shows an integer. Write has_groups_size_x(deck: list[int]) -> bool: can the whole deck be split into groups so that

  • every group has the same size X, with X ≥ 2, and
  • every card in a group shows the same number?
has_groups_size_x([4, 4, 9, 9, 9, 9])      # True  (X = 2: [4,4], [9,9], [9,9])
has_groups_size_x([1, 1, 1, 2, 2])         # False (counts 3 and 2 share no divisor ≥ 2)
has_groups_size_x([6])                     # False (a group needs at least 2 cards)
has_groups_size_x([5, 5, 5, 5, 5, 5, 8, 8, 8, 8])  # True  (X = 2)

Constraints: 1 ≤ len(deck) ≤ 10^4, 0 ≤ deck[i] < 10^4.

Show hint

A value that appears c times can be split into groups of size X exactly when X divides c. So what must be true of all the counts together?

Topic: Primes, divisors and GCD. Sieve, trial division to sqrt(n), Euclid's algorithm.

0:00
Ctrl ' run · Ctrl ↵ submit
esc