← Questions

Deck of cards with shuffle, draw and sort

0
AppleOO designLast asked Mar 2026

An object-oriented design interview question asked in Apple's technical phone screen, last asked Mar 2026. It tests object-oriented design and randomization.

Design an in-memory model of a standard 52-card deck. Client code builds a fresh deck, shuffles it, draws cards one at a time until the deck is empty, and can put the remaining cards back in order. Walk through the classes, the data structure, the algorithms and why the randomness is fair.

Requirements

  • Functional:
    • Card: an immutable value with a rank (Ace through King) and a suit (Clubs, Diamonds, Hearts, Spades), with equality and a readable string form.
    • Deck: owns its cards and a random number source. shuffle() randomizes the order of the cards still in the deck. draw() removes and returns one card. sort() puts the remaining cards in order by suit, then rank. size() tells how many are left.
    • After shuffle(), every ordering of the remaining cards is equally likely. Each draw() returns each remaining card with equal probability.
    • A drawn card is gone until the deck is reset.
  • Non-functional: shuffle() in O(n) time and O(1) extra space; draw() in O(1); deterministic tests through an injectable random source.

Clarifying questions

  • Does shuffle() mix only the remaining cards, or reset to 52 first?
  • What should draw() do on an empty deck: raise, or return an empty value?
  • Is the deck used from several threads at once?
  • Are jokers or multi-deck shoes ever needed?
  • Is ace high or low when sorting?

What a strong answer covers

  • A clean split: immutable Card values, enums for rank and suit, a Deck container built from the cross product of 4 suits and 13 ranks.
  • A list with one end as the top: draw() pops from the end in O(1); random indexing makes the shuffle cheap.
  • The Fisher-Yates shuffle stated exactly (for i from n-1 down to 1, pick j uniformly in [0, i], swap), why it gives all n! orders equally, and the biased versions to avoid (picking j from the whole range each step, sorting by random keys).
  • A uniform draw() that doesn't depend on a prior shuffle: pick a random index, swap it with the last card, pop.
  • sort() with an explicit order on suit and rank, not string comparison.
  • Testing randomness: a seeded source for deterministic tests, and a frequency or chi-square test over many shuffles for fairness.

Follow-ups

  • Support a six-deck shoe with a discard pile and a reshuffle that folds the discards back in.
  • Two players draw from the same deck at once: how do you keep a card from being dealt twice?
  • Draw with replacement from an endless stream of cards.

Where it's asked

  • Apple · Technical phone screen · Last asked Mar 2026

What it tests

object-oriented design · randomization

Your canvas
Draw your answer hereBoxes, arrows and notes, saved for you to come back to.Sign in to start drawing