Start learning free

LESSON 671 OF 673 · OBJECT-ORIENTED DESIGN - INTERVIEWS

Deck of Cards in Python: deque, Cut and Perfect Shuffle

Practice O(n) Read the full explanation

This is a design round. You write the classes, and the interviewer checks that they behave.

Here you build a deck of playing cards. You can cut it, shuffle it and deal from it.

A card has a rank and a suit. The ranks in order are A 2 3 4 5 6 7 8 9 10 J Q K. The suits in order are C D H S (clubs, diamonds, hearts and spades).

Implement two classes:

  • Card(rank, suit) makes a card.
  • The card's label() returns its rank and then its suit, such as "10H".
  • Deck() makes a new deck of 52 cards.
  • cut(k) moves the top k cards to the bottom. They keep their order.
  • perfect_shuffle() splits the deck into a top half and a bottom half. Then it takes one card from each half in turn, starting with the top half.
  • deal(count) takes count cards off the top and returns them, top card first. If fewer cards are left, it returns all of them.
  • remaining() returns how many cards are left.

A new deck holds the clubs from A to K, then the diamonds, hearts and spades. So AC is on top and KS is at the bottom.

When the number of cards is odd, the top half gets the extra card. For example, the five cards 1 2 3 4 5 shuffle into 1 4 2 5 3. Nothing here is random.

The calls run in order on one new deck. The output has one line for each deal and remaining call. A deal line lists the labels with a space between them. It says none when no card was dealt.

 

Example 1:

Input:
Deck()
1. deal(3)
2. remaining()
3. cut(10)
4. deal(2)
5. remaining()
Output:
AC 2C 3C
49
AD 2D
47
Explanation:
Call 1 deals the top three clubs.
Call 3 moves the other ten clubs to the bottom.
So the diamonds are on top for call 4.

Example 2:

Input:
Deck()
1. perfect_shuffle()
2. deal(4)
3. remaining()
Output:
AC AH 2C 2H
48
Explanation:
The top half holds the clubs and the diamonds.
The bottom half holds the hearts and the spades.
So the shuffled deck starts with AC, AH, 2C and 2H.

Example 3:

Input:
Deck()
1. perfect_shuffle()
2. perfect_shuffle()
3. perfect_shuffle()
4. perfect_shuffle()
5. perfect_shuffle()
6. perfect_shuffle()
7. perfect_shuffle()
8. perfect_shuffle()
9. deal(5)
Output:
AC 2C 3C 4C 5C
Explanation:
Eight perfect shuffles bring a full deck back to its first order.

 

Constraints:

  • k is a whole number from 0 to the number of cards left.
  • count is a whole number from 1 to 1,000,000,000.
  • At most 1,000 calls are made on one deck.

Note:

Each call should take at most O(n) time, where n is the number of cards in the deck. That holds for deal too, even when it asks for more cards than are left.

STEP 1 OF 20
    Ctrl + Enter to check

    PYTHON · OBJECT-ORIENTED DESIGN - INTERVIEWS

    Deck Of Cards in Python, explained

    Problem overview

    You write two classes. A Card has a rank and a suit, and its label() joins them, as in "10H". A Deck holds 52 cards and supports cut(k), perfect_shuffle(), deal(count) and remaining(). The lesson's tests make one deck, call the methods in order and print each deal as labels separated by spaces (or none for an empty hand) and each remaining as a number.

    A new deck is ordered by suit, then rank: the clubs AC 2C ... KC, then diamonds, hearts and spades, so AC is on top and KS at the bottom. Nothing is random.

    • cut(k) moves the top k cards to the bottom, keeping their order.
    • perfect_shuffle() splits the deck into a top half and a bottom half, then takes one card from each half in turn, top half first. With an odd count the top half gets the extra card: 1 2 3 4 5 becomes 1 4 2 5 3.
    • deal(count) removes count cards from the top and returns them, top card first, or all that are left if there are fewer.

    For example, a new deck dealt three cards gives AC 2C 3C and leaves 49. After perfect_shuffle() on a new deck, the first four cards are AC AH 2C 2H: the top half is the clubs and diamonds, the bottom half the hearts and spades, and the shuffle alternates between them.

    Approach: a queue for the cards, a list for the shuffle

    The deck is a sequence where cards leave from the top and, after a cut, return at the bottom. Python's collections.deque is built for that: popleft() removes from the front and append() adds at the back, both in O(1). A plain list would make pop(0) shift every other card, which costs O(n) each time. So the front of the deque is the top of the deck.

    A cut is then a loop that runs k times, each time moving the front card to the back. One card at a time keeps the moved cards in their order, and the cut costs O(k).

    The shuffle needs to read card i of each half, and a deque is slow at reading the middle. So the shuffle copies the cards into a list order, where any position is O(1), and builds the deck again from it. The top half has (len(order) + 1) // 2 cards: the + 1 hands the extra card of an odd count to the top half (5 cards give 3 and 2; 52 give 26 and 26). In round i, the card order[i] from the top half goes in, then order[half + i] from the bottom half, if one exists.

    Dealing must not loop count times, since count can be a billion. The loop instead stops when the hand is full or the deck is empty, so it runs at most 52 times.

    Step by step

    1. Store rank and suit in the Card constructor, as public fields: the program reads every card's data.
    2. Return rank plus suit from label. Adding two strings joins them.
    3. Create an empty deque in Deck.__init__, as the private field _cards.
    4. Write the suits and ranks in order as two lists.
    5. Use two nested loops, suits outside and ranks inside, appending a new Card(rank, suit) each time. This makes 4 × 13 = 52 cards with the clubs first.
    6. Cut: repeat k times, popping the front card and appending it at the back.
    7. Shuffle: copy the cards to a list, reset the deque to empty, compute the size of the top half, and loop over range(half).
    8. In each shuffle round, append the top-half card, then append the bottom-half card only if its position is still inside the list.
    9. Deal: collect cards into a list while it is shorter than count and the deck isn't empty, then return the list.
    10. Remaining: return the length of the deque.

    The solution in Python

    class Card:
        def __init__(self, rank, suit):
            self.rank = rank
            self.suit = suit
    
        def label(self):
            return self.rank + self.suit
    
    class Deck:
        def __init__(self):
            self._cards = deque()
            suits = ["C", "D", "H", "S"]
            ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
            for suit in suits:
                for rank in ranks:
                    self._cards.append(Card(rank, suit))
    
        def cut(self, k):
            for _ in range(k):
                self._cards.append(self._cards.popleft())
    
        def perfect_shuffle(self):
            order = list(self._cards)
            self._cards = deque()
            half = (len(order) + 1) // 2
            for i in range(half):
                self._cards.append(order[i])
                if half + i < len(order):
                    self._cards.append(order[half + i])
    
        def deal(self, count):
            hand = []
            while len(hand) < count and len(self._cards) > 0:
                hand.append(self._cards.popleft())
            return hand
    
        def remaining(self):
            return len(self._cards)

    The solution uses deque from the collections module. In a file of your own, add from collections import deque at the top.

    Notes on the code:

    • for _ in range(k) uses _ for a loop variable the body doesn't need.
    • self._cards.append(self._cards.popleft()) works because popleft() returns the card it removes.
    • Both len(self._cards) and list(self._cards) work on a deque as on a list.
    • The shuffle assigns a new deque to self._cards instead of clearing the old one. That is fine because order already holds the old cards.
    • A deal returns Card objects, not strings. To print them, call label() on each one.

    Using the classes:

    deck = Deck()
    print(" ".join(c.label() for c in deck.deal(3)), deck.remaining())
    deck.cut(10)
    print(" ".join(c.label() for c in deck.deal(2)), deck.remaining())
    
    deck = Deck()
    deck.perfect_shuffle()
    print(" ".join(c.label() for c in deck.deal(4)), deck.remaining())
    
    deck = Deck()
    for _ in range(8):
        deck.perfect_shuffle()
    print(" ".join(c.label() for c in deck.deal(5)))
    AC 2C 3C 49
    AD 2D 47
    AC AH 2C 2H 48
    AC 2C 3C 4C 5C

    The last line shows that eight perfect shuffles bring a 52-card deck back to its starting order. Dealing more than is left, such as deal(1000000000) on a deck with 2 cards, returns those 2 cards and leaves remaining() at 0.

    Complexity

    Building the deck is O(n) for n = 52 cards. cut(k) costs O(k), and since k is at most the number of cards, it is O(n). perfect_shuffle copies the cards and rebuilds the deck: O(n) time and O(n) extra space for the list. deal removes at most n cards, so it is O(n) even for a huge count, and remaining is O(1).

    Edge cases and common mistakes

    • Looping count times in deal. With a count of a billion, that never finishes and fails once the deck is empty. Stop when the deck is empty.
    • Using a list with pop(0). It works, but every removal shifts all the remaining cards. A deque is the right tool.
    • Half size with len // 2. For an odd count the top half would be one card short, and the shuffle would lose the last card (5 cards would give 1 3 2 4). Use (len + 1) // 2.
    • Reading past the end in the shuffle. With an odd count, the last round has no bottom card. The if half + i < len(order) test skips it.
    • Shuffling in place while reading. Rebuilding from the same deque you are reading mixes up old and new positions. Copy first.
    • Cutting by 0 or by the whole deck. Both leave the order unchanged, and the loop handles them with no special case.
    • Dealing from an empty deck. The result is an empty list, which the tests print as none.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free