N data structures cheat sheet: which of the 5 to reach for, with the python for each - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/data-structures-cheat-sheet/
☷ data structures cheat sheet: which of the 5 to reach for, with the python for each - nicnonac guides _□×

← back to guides

data structures cheat sheet: which of the 5 to reach for, with the python for each

Stacks · 9 min read · posted Nov 29, 2026, 10:10 pm

Most coding interview questions get a lot easier once you pick the right data structure. Each one is good at one thing, and the question usually tells you which one it wants.

This is the cheat sheet from the reel. It covers the five structures in it. For each one you get the signals that give it away in a question, the Python, the mistake that usually breaks it, and problems to practise on, easiest first.

Four of these five have their own file in the notes I made over about three months of preparing for my Atlassian internship interviews: hashing, stack, heap and graphs. The trie is the one I added for this. None of the problems below come from an interview. They're all public on LeetCode.

the quick lookup

Read the question and look for these words before you write anything.

the question says reach for
"have I seen this before", count things, find a pair, group things hash map
matching brackets, nested things, undo, "next greater" stack
"k largest", "k closest", top k, always needs the current smallest heap
prefix, autocomplete, "starts with", a dictionary of words trie
connections, dependencies, a network, "can you get from A to B" graph

what each one costs

structure what it's fast at cost
hash map look up, add or delete by key O(1) on average
stack push, pop, look at the top O(1)
heap read the smallest, then push or pop O(1) to read, O(log n) to push or pop
trie add or find a word of length L O(L), however many words are stored
graph (adjacency list) list one node's neighbours, or visit everything O(1) to reach the list, O(V + E) for a full visit

1. hash map

Spot it. You need to remember things you've already seen and ask about them instantly. Counting how often something appears, finding a pair that adds up to a target, and grouping things that share a property are all the same move.

The idea. A hash map stores key and value pairs and finds a key in O(1) on average. You spend memory to save time. "Check every pair", which is O(n²), turns into one pass, O(n).

Template: have I seen its partner?

def two_sum(nums, target):
    seen = {}                      # value -> index
    for i, n in enumerate(nums):
        want = target - n
        if want in seen:
            return [seen[want], i]
        seen[n] = i
    return []

This is the one in the reel. The target is 14, and when the loop reaches 6 it finds 8 already in the map, so the answer is indexes 1 and 5.

Second shape: group by a key. Words that are anagrams of each other have the same letters, so the sorted letters make a key they all share.

from collections import defaultdict

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

For plain counting, collections.Counter(nums) gives you the whole tally in one line.

What breaks it. Storing before checking. In two sum, if you put the number in the map first, a target of 6 matches a single 3 with itself. Check, then store. The other one is the key: a list can't be a key in Python, so turn it into a tuple or a string first.

Practise.

2. stack

Spot it. Brackets that have to match, anything nested, undo, and "the next greater element". What they share: the thing you need next is always the most recent thing you haven't dealt with yet.

The idea. Last in, first out. In Python a list is already a stack: append pushes and pop takes the newest item off.

Template: matching pairs.

def is_valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for c in s:
        if c in pairs:                                  # a closing bracket
            if not stack or stack.pop() != pairs[c]:
                return False
        else:
            stack.append(c)                             # an opening bracket waits
    return not stack

In the reel this runs on {[()]}. It pushes three opening brackets, pops them in reverse as each one is closed, and ends with an empty stack, which means valid.

Second shape: the monotonic stack. The stack holds the days still waiting for a warmer one. A new temperature settles every waiting day that is colder than it.

def daily_temperatures(temps):
    answer = [0] * len(temps)
    stack = []                                          # indexes still waiting
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            answer[j] = i - j
        stack.append(i)
    return answer

What breaks it. Popping from an empty stack. A string that starts with ) has nothing to pop, so check not stack first. The other one is forgetting the last line: ((( never fails inside the loop, and it's only the leftover items that make it invalid.

Practise.

3. heap

Spot it. "The k largest", "the k closest", "the k most frequent". Also anything where you keep adding items and keep needing the smallest or the biggest one, like a running median or merging sorted lists.

The idea. A heap always knows its smallest item. Reading it is O(1), and adding or removing costs O(log n). Python's heapq is a min-heap, so the smallest is at heap[0].

Template: keep a heap of size k.

import heapq

def kth_largest(nums, k):
    heap = []
    for n in nums:
        heapq.heappush(heap, n)
        if len(heap) > k:
            heapq.heappop(heap)     # the smallest can't be in the top k
    return heap[0]

The trick is that it's a min-heap holding the k biggest numbers so far, so the smallest of those is the kth largest. In the reel the numbers are 5, 2, 9, 1, 7, 6 with k = 3. The heap ends up holding 6, 7 and 9, and the answer is 6. This is O(n log k). Sorting everything first is O(n log n).

Second shape: you need the biggest. There's no max-heap in heapq, so store the negatives.

import heapq

def last_stone_weight(stones):
    heap = [-s for s in stones]
    heapq.heapify(heap)
    while len(heap) > 1:
        a = -heapq.heappop(heap)    # heaviest
        b = -heapq.heappop(heap)    # second heaviest
        if a != b:
            heapq.heappush(heap, -(a - b))
    return -heap[0] if heap else 0

What breaks it. Treating the heap as a sorted list. Only heap[0] is guaranteed, and the rest is in heap order, not sorted order. With the negation trick, the usual bug is forgetting to flip the sign back when you read a value out.

Practise.

4. trie

Spot it. The word "prefix". Autocomplete, "starts with", or a big dictionary of words you'll search many times.

The idea. A tree where every step down is one letter. Words that start the same way share the same path, so finding a word costs its own length, however many words are stored.

Template.

class Trie:
    def __init__(self):
        self.root = {}

    def insert(self, word):
        node = self.root
        for c in word:
            node = node.setdefault(c, {})   # follow the letter, or add it
        node["end"] = True                  # a word stops here

    def _walk(self, s):
        node = self.root
        for c in s:
            if c not in node:
                return None
            node = node[c]
        return node

    def search(self, word):
        node = self._walk(word)
        return node is not None and "end" in node

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

Each node is a dictionary from a letter to the next node. In the reel the words are tree, trie and try. They share the path t, r, so those two nodes are stored once and the three words branch after them.

What breaks it. Leaving out the end marker. After you insert "tree", starts_with("tre") should be true and search("tre") should be false, and the marker is the only thing that tells them apart. Also check you need one at all: if every lookup is for a whole word, a set is simpler and just as fast.

Practise.

5. graph

Spot it. Things connected to other things: friends, flights, courses with prerequisites, cells in a grid. The question asks whether you can get from A to B, how many separate groups there are, or what order to do things in. It often never says the word graph.

The idea. Store it as an adjacency list: a dictionary from each node to the list of its neighbours. Then every question becomes a walk over that dictionary.

Template: build it, then walk it.

from collections import defaultdict, deque

def build(edges):
    graph = defaultdict(list)
    for a, b in edges:
        graph[a].append(b)
        graph[b].append(a)      # leave this line out for a one-way edge
    return graph

def path_exists(edges, start, goal):
    graph = build(edges)
    seen, q = {start}, deque([start])
    while q:
        node = q.popleft()
        if node == goal:
            return True
        for nxt in graph[node]:
            if nxt not in seen:
                seen.add(nxt)
                q.append(nxt)
    return False

The reel builds the list from seven edges between A and F. Each edge goes into both nodes' lists, and D ends up with B, C, E and F. The walk here is a breadth-first search. When to use that and when to use depth-first is in the coding interview cheat sheet.

What breaks it. No seen set. A tree has no way back up, but a graph can have loops, and without seen you walk in circles forever. The other one is nodes with no edges: they never appear in the dictionary, so if the question gives you n nodes, loop over all n when you count groups.

Practise.

how to practise with this

One structure at a time. Do the easy problem with the template open, then the mediums with it closed. When you're stuck, go back to the quick lookup and ask what the question needs to be fast, before you look at a solution.

In the interview, say the structure and the reason out loud before you write code. "I need to know if I've seen a number before, so I'll keep a hash map" tells the interviewer more than silent typing does.

honest limitations

Five structures isn't the full set. Arrays, strings, linked lists, queues and binary trees come up at least as often, and they're simple enough that they rarely feel like a choice.

Knowing the structure is half of it. The other half is the pattern you run on top, like two pointers or BFS, and those are in the coding interview cheat sheet. The order I'd learn everything in is in my big tech internship prep guide.

Everything here is Python. The ideas carry over to any language, but heapq, defaultdict and deque are Python's.

← all guides

Done nicnonac.com 56.6k