Build a Playing-Card Deck with Fair Shuffle and Custom Sort
Data Structure DesignModel answerLast 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
- State explicitly your rank order (including where 2 and Ace go, since the example starts at 3) and your suit order.
- Describe the data model and data structures you would choose for suits, ranks, cards and the deck.
- Explain the algorithm for
shuffle()and argue why it is unbiased. - Explain how
order()works. - Give time and space complexity for construction,
shuffle()andorder(). - Write the code in a language of your choice.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract
The example begins at rank 3, so the first question is where 2 goes. I would ask, then state an assumption:
- Rank order (low to high): 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A, 2. This is the ordering the example implies. If the interviewer wants 2 at the bottom, only the rank enum changes.
- Suit order (low to high): Clubs < Diamonds < Hearts < Spades.
order(): sorts by rank, then suit: C3, D3, H3, S3, C4, ..., S2.shuffle(): produces a uniformly random permutation, with each of the 52! arrangements having probability exactly 1/52!. It also updates the deck's current arrangement.
Data model
SuitandRankas integer enums. The integer value is the sort position, so the ordering is defined once.Cardas an immutable value object(rank, suit). It is hashable and comparable. Declaring the fields rank-first makes tuple comparison equal to "rank then suit".Deckwraps a list of 52 cards. A list gives O(1) indexed swaps, which the shuffle needs.
Every card has a unique index rank * 4 + suit in 0..51, which is its position in the canonical order. That allows order() in O(n) by placing each card into its slot instead of comparing. For 52 cards either approach is fine, but the observation is worth mentioning.
Shuffle: Fisher-Yates
For i from 51 down to 1, choose j uniformly in [0, i] (inclusive) and swap cards[i] with cards[j].
Why it is unbiased. The algorithm makes independent choices with 52, 51, ..., 2 options, giving exactly 52! equally likely paths. Each path ends in a distinct permutation, because position i is final once step i completes. The mapping from paths to permutations is therefore one-to-one, so each permutation has probability 1/52!.
Common biased variants:
- Swap with any index in 0..51 at every step. That gives 52^52 paths. Since 52^52 is not a multiple of 52!, some permutations must be more likely than others.
- Sorting with a random comparator. The comparator is inconsistent, the result depends on the sort implementation, and the distribution is not uniform.
- Modulo bias. Reducing a fixed-range random integer with
%favors small values. Use a library call that does rejection sampling, or implement it yourself. - Off-by-one on the range. Choosing
jin[0, i)is Sattolo's algorithm, which only yields cyclic permutations.
Randomness source. log2(52!) is about 226 bits, so a generator seeded with 32 bits can reach only a tiny fraction of arrangements. That is fine for a casual game. For anything where predictability costs money, use an OS-backed cryptographic source. Make the RNG injectable so tests can be deterministic.
Order
Simplest: sorted(cards) using the (rank, suit) comparison. For a stricter O(n) version, allocate an array of 52 slots and put each card at its sort_index. The output must not depend on the current shuffle state.
Complexity
| Operation | Time | Extra space |
|---|---|---|
| Construction | O(n) | O(n) |
shuffle() | O(n): n-1 random draws and swaps | O(1) in place, O(n) for a returned copy |
order() | O(n log n) with a sort, O(n) with slot placement | O(n) for the output |
With n = 52 all of this is effectively constant, but the same analysis holds for multi-deck shoes or other deck sizes.
Code (Python)
from __future__ import annotations
import random
from dataclasses import dataclass
from enum import IntEnum
from typing import List, Optional
class Suit(IntEnum):
CLUBS = 0
DIAMONDS = 1
HEARTS = 2
SPADES = 3
class Rank(IntEnum):
THREE = 0; FOUR = 1; FIVE = 2; SIX = 3; SEVEN = 4
EIGHT = 5; NINE = 6; TEN = 7; JACK = 8; QUEEN = 9
KING = 10; ACE = 11; TWO = 12
@dataclass(frozen=True, order=True)
class Card:
rank: Rank # declared first so comparison is rank, then suit
suit: Suit
@property
def sort_index(self) -> int:
return int(self.rank) * len(Suit) + int(self.suit)
class Deck:
def __init__(self, rng: Optional[random.Random] = None) -> None:
self._rng = rng or random.Random()
self._cards: List[Card] = [Card(r, s) for r in Rank for s in Suit]
def shuffle(self) -> List[Card]:
cards = self._cards
for i in range(len(cards) - 1, 0, -1):
j = self._rng.randint(0, i) # inclusive upper bound
cards[i], cards[j] = cards[j], cards[i]
return list(cards) # defensive copy
def order(self) -> List[Card]:
slots: List[Optional[Card]] = [None] * len(self._cards)
for c in self._cards:
slots[c.sort_index] = c
return [c for c in slots if c is not None]
Edge cases and design points
- Return copies, not the internal list, so callers cannot corrupt deck state.
- Invariants: exactly 52 unique cards before and after every call. Assert this in tests.
- Testing uniformity: you cannot enumerate 52! outcomes. Shuffle a 4-card deck (24 permutations) around 10^5 times and run a chi-square test, and for the full deck check that each card lands in each position about 1/52 of the time. Also test with a seeded RNG for reproducibility.
- Extensibility: jokers or multiple decks mean changing the enums or constructor. The slot-placement trick breaks with duplicate cards, but sorting with a key still works.
- Common mistakes: forgetting to define the position of 2, sorting by suit first instead of rank first, a biased shuffle, and exposing mutable internal state.