KatInterview

Equal-Sized Uniform Piles From a Card Collection

Math & Bit ManipulationAuto-graded · 25 test cases
EasyAuto-gradedMath & Bit Manipulationgcdhash-mapcounting

Last updated

Decide whether a multiset of integers can be split into uniform piles that all share one common size of at least two, testing counting and the GCD insight.

You are given a list of integers cards, where each integer is the value printed on a card.

You want to arrange every card into piles so that:

  • each pile contains cards of one single value only,
  • every pile contains exactly the same number of cards, call it s, and
  • s is at least 2.

Return True if some choice of s makes this possible, and False otherwise.

Every card must be placed in exactly one pile. Different piles may hold the same value, so a value that appears many times can be split across several piles.

If cards is empty, return False, since no valid pile size can be chosen.

Constraints

  • 0 <= len(cards) <= 10^4
  • 0 <= cards[i] < 10^4
  • The return value is a boolean (True or False).

Examples

Example 1

Input: can_form_equal_piles([1, 2, 3, 4, 4, 3, 2, 1])

Output: True

Example 2

Input: can_form_equal_piles([1, 1, 1, 2, 2, 2, 3, 3])

Output: False

Example 3

Input: can_form_equal_piles([1])

Output: False

Hints

Hint 1

Look at each distinct value on its own: if a value appears c times, which pile sizes can split exactly c cards into equal piles?

Hint 2

The same pile size s must work for every distinct value, so s must divide every one of the occurrence counts.

Hint 3

A common divisor of at least 2 exists exactly when the greatest common divisor of all the counts is at least 2. Fold gcd across the counts.