KatInterview

Build a Playing-Card Deck with Fair Shuffle and Custom Sort

Data Structure DesignModel answer
MediumModel answerData Structure Designobject-oriented-designshufflefisher-yates

Last updated

Model a 52-card deck, return an unbiased random permutation, and list the cards in a defined rank-then-suit order, with data structures and complexity explained.

You are asked to design a small library that represents a standard 52-card playing deck. It must expose two operations:

  • shuffle() returns the cards in a uniformly random order, so each of the 52! possible arrangements is equally likely.
  • order() returns all cards in a fixed canonical order: sorted by rank first, and by suit when ranks are equal.

The expected canonical order starts like this:

Clubs-3, Diamonds-3, Hearts-3, Spades-3, Clubs-4, Diamonds-4, Hearts-4, Spades-4, ...

and continues through every rank in the same suit order.

What to cover in your answer

  1. State explicitly your rank order (including where 2 and Ace go, since the example starts at 3) and your suit order.
  2. Describe the data model and data structures you would choose for suits, ranks, cards and the deck.
  3. Explain the algorithm for shuffle() and argue why it is unbiased.
  4. Explain how order() works.
  5. Give time and space complexity for construction, shuffle() and order().
  6. Write the code in a language of your choice.
  7. Mention edge cases, API pitfalls, and how you would test the result.

Hints

Hint 1

Ambiguity first: the example starts at rank 3, so decide and state where 2 and Ace sit. Make the ordering live in exactly one place, such as an enum whose integer values define sort position.

Hint 2

For a fair shuffle, think about how many equally likely execution paths your algorithm has and whether that number matches the number of permutations (52!). Walk the array from the end and swap each position with a random position chosen from the unplaced prefix, including itself.

Hint 3

Watch for classic bugs: picking the swap partner from the whole array every time, excluding the current index from the range, using a biased comparator in a sort, or using a modulo on a fixed-range random number. Also decide whether methods return the internal list or a copy.