Skip to the content.

Interviews Cheat Sheets: Big-O, Data Structures, Algorithms, OS, Networking, Databases and System Design Numbers

Interviews cheat sheets for coding and technical interview preparation: one page per topic. Each sheet covers one topic: Big-O complexity, arrays and strings, linked lists, trees, graphs, dynamic programming, hashing, heaps, bit manipulation, sorting and searching, operating systems, networking, databases, concurrency and back-of-the-envelope system design numbers. Every code snippet is short, standard-library Python 3 and runnable as written, with asserts that act as tests. Use it for a last-hour review before a coding interview, or as a quick reference while practising.

Last reviewed: December 2026

License: content and code are MIT licensed (see LICENSE). This is an independent project, not affiliated with any company or other interview repository.

Table of Contents

  1. Big-O Complexity
  2. Arrays and Strings
  3. Hashing and Hash Tables
  4. Linked Lists
  5. Stacks and Queues
  6. Trees and Tries
  7. Heaps and Priority Queues
  8. Graphs
  9. Sorting and Searching
  10. Dynamic Programming
  11. Backtracking
  12. Bit Manipulation
  13. Operating Systems
  14. Networking
  15. Databases
  16. Concurrency
  17. System Design Numbers

Each section is also available as a standalone file in sheets/.


1. Big-O Complexity

Big-O describes how running time or memory grows as input size n grows, ignoring constant factors and lower-order terms. In interviews, “complexity” usually means the worst case unless you say otherwise.

Growth rates, fastest to slowest

Notation Name Example n = 1,000 (approx. operations)
O(1) Constant Array index, hash lookup (average) 1
O(log n) Logarithmic Binary search, balanced BST lookup ~10
O(n) Linear Scan an array 1,000
O(n log n) Linearithmic Merge sort, heap sort ~10,000
O(n^2) Quadratic Nested loops over pairs 1,000,000
O(n^3) Cubic Floyd-Warshall, naive matrix multiply 10^9
O(2^n) Exponential All subsets ~10^301
O(n!) Factorial All permutations astronomically large

Rules of thumb

What input size suggests what complexity

A typical judge runs on the order of 10^7 to 10^8 simple operations per second (much less in pure Python). Use this to guess the intended solution:

n up to Usually acceptable
~10 O(n!) , O(2^n * n)
~20 O(2^n)
~500 O(n^3)
~5,000 O(n^2)
~10^6 O(n log n) or O(n)
~10^9 or more O(log n) or O(1)

Python built-in operation costs (CPython, average case)

Operation list dict / set collections.deque
Index x[i] O(1) n/a O(n) (O(1) at either end)
Append / add O(1) amortized O(1) O(1) at either end
Pop from end O(1) n/a O(1) at either end
Pop / insert at front O(n) n/a O(1)
Insert / delete in middle O(n) n/a O(n)
x in c O(n) O(1) O(n)
Iterate O(n) O(n) O(n)
len(c) O(1) O(1) O(1)
Sort O(n log n) n/a n/a
Copy / slice of length k O(k) O(n) copy O(n)

Dict and set operations are O(1) on average and O(n) in the pathological worst case (many keys colliding).


2. Arrays and Strings

Key facts

Core patterns

Pattern When to use Typical cost
Two pointers Sorted array, pairs, palindromes, in-place partitioning O(n)
Sliding window Longest/shortest subarray or substring meeting a condition O(n)
Prefix sums Many range-sum queries, subarray sum equals k O(n) build, O(1) query
Hash map counting Anagrams, frequencies, “seen before” checks O(n)
Kadane’s algorithm Maximum subarray sum O(n)
Binary search Sorted data or a monotonic yes/no condition O(log n)

Snippets

# Two pointers: pair with target sum in a sorted array.
def pair_sum_sorted(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None

assert pair_sum_sorted([1, 3, 4, 6, 9], 10) == (0, 4)
assert pair_sum_sorted([1, 2], 7) is None


# Hash map: two sum on an unsorted array, O(n).
def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return seen[target - x], i
        seen[x] = i
    return None

assert two_sum([2, 7, 11, 15], 9) == (0, 1)


# Sliding window: length of the longest substring without repeating characters.
def longest_unique_substring(s):
    last = {}
    start = best = 0
    for i, ch in enumerate(s):
        if ch in last and last[ch] >= start:
            start = last[ch] + 1
        last[ch] = i
        best = max(best, i - start + 1)
    return best

assert longest_unique_substring("abcabcbb") == 3
assert longest_unique_substring("bbbb") == 1
assert longest_unique_substring("") == 0


# Prefix sums: count subarrays whose sum equals k (works with negatives).
from collections import defaultdict

def subarray_sum_count(nums, k):
    counts = defaultdict(int)
    counts[0] = 1
    total = result = 0
    for x in nums:
        total += x
        result += counts[total - k]
        counts[total] += 1
    return result

assert subarray_sum_count([1, 1, 1], 2) == 2
assert subarray_sum_count([1, -1, 0], 0) == 3


# Kadane: maximum subarray sum (non-empty).
def max_subarray(nums):
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

assert max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6
assert max_subarray([-3, -1, -2]) == -1


# Strings: anagram check and palindrome check.
from collections import Counter

def is_anagram(a, b):
    return Counter(a) == Counter(b)

def is_palindrome(s):
    cleaned = [c.lower() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]

assert is_anagram("listen", "silent")
assert is_palindrome("A man, a plan, a canal: Panama")

3. Hashing and Hash Tables

How a hash table works

  1. A hash function maps a key to an integer; the table uses it (mod the table size) to pick a slot.
  2. Two keys landing in the same slot is a collision. Two common fixes:
    • Separate chaining: each slot holds a small list of entries. Java’s HashMap does this (and converts long chains to balanced trees since Java 8).
    • Open addressing: on collision, probe other slots. CPython’s dict and set do this.
  3. The load factor is entries / slots. When it passes a threshold, the table grows (typically doubling) and rehashes everything. Growth is O(n) but rare, so inserts stay O(1) amortized.
Operation Average Worst
Insert O(1) O(n)
Lookup O(1) O(n)
Delete O(1) O(n)

Rules

from collections import Counter, defaultdict

# Group anagrams: the sorted string (or a letter-count tuple) is the key.
def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return sorted(sorted(g) for g in groups.values())

assert group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) == [
    ["ate", "eat", "tea"], ["bat"], ["nat", "tan"]
]

# Top-k frequent elements.
def top_k(nums, k):
    return [x for x, _ in Counter(nums).most_common(k)]

assert top_k([1, 1, 1, 2, 2, 3], 2) == [1, 2]

# Longest consecutive sequence in O(n) using a set.
def longest_consecutive(nums):
    s = set(nums)
    best = 0
    for x in s:
        if x - 1 not in s:  # only start counting at the beginning of a run
            length = 1
            while x + length in s:
                length += 1
            best = max(best, length)
    return best

assert longest_consecutive([100, 4, 200, 1, 3, 2]) == 4

4. Linked Lists

Complexity

Operation Singly linked list Doubly linked list Dynamic array
Access k-th element O(k) O(k) O(1)
Insert/delete at head O(1) O(1) O(n)
Insert/delete at tail O(1) with tail pointer (delete is O(n) for singly) O(1) O(1) amortized
Insert/delete after a known node O(1) O(1) O(n)
Search O(n) O(n) O(n)

Techniques

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def from_list(values):
    dummy = ListNode()
    tail = dummy
    for v in values:
        tail.next = ListNode(v)
        tail = tail.next
    return dummy.next

def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out

def reverse(head):
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev

def middle(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
    return slow  # second middle for even lengths

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow, fast = slow.next, fast.next.next
        if slow is fast:
            return True
    return False

def merge_sorted(a, b):
    dummy = tail = ListNode()
    while a and b:
        if a.val <= b.val:
            tail.next, a = a, a.next
        else:
            tail.next, b = b, b.next
        tail = tail.next
    tail.next = a or b
    return dummy.next

def remove_nth_from_end(head, n):
    dummy = ListNode(0, head)
    fast = slow = dummy
    for _ in range(n + 1):
        fast = fast.next
    while fast:
        fast, slow = fast.next, slow.next
    slow.next = slow.next.next
    return dummy.next

assert to_list(reverse(from_list([1, 2, 3]))) == [3, 2, 1]
assert middle(from_list([1, 2, 3, 4, 5])).val == 3
assert to_list(merge_sorted(from_list([1, 3, 5]), from_list([2, 4]))) == [1, 2, 3, 4, 5]
assert to_list(remove_nth_from_end(from_list([1, 2, 3, 4, 5]), 2)) == [1, 2, 3, 5]
cyc = from_list([1, 2, 3])
cyc.next.next.next = cyc.next
assert has_cycle(cyc) and not has_cycle(from_list([1, 2]))

5. Stacks and Queues

Structure Order Python Push / pop cost
Stack Last in, first out list with append / pop O(1)
Queue First in, first out collections.deque with append / popleft O(1)
Deque Both ends collections.deque O(1) at both ends
Thread-safe queue FIFO across threads queue.Queue O(1)

Do not use list.pop(0) as a queue: it is O(n).

Use a stack for: matching brackets, undo, DFS without recursion, evaluating expressions, and monotonic stack problems (next greater element, daily temperatures, largest rectangle in histogram).

Use a queue for: BFS, task scheduling, sliding window maximum (with a monotonic deque).

from collections import deque

def valid_brackets(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack

assert valid_brackets("([]{})") and not valid_brackets("(]")

# Monotonic stack: for each day, how many days until a warmer temperature.
def days_until_warmer(temps):
    result = [0] * len(temps)
    stack = []  # indices with decreasing temperatures
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            result[j] = i - j
        stack.append(i)
    return result

assert days_until_warmer([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]

# Monotonic deque: maximum of each window of size k, O(n).
def window_max(nums, k):
    dq, out = deque(), []
    for i, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

assert window_max([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]

6. Trees and Tries

Vocabulary

Complexity

Operation Balanced BST Unbalanced BST (worst)
Search / insert / delete O(log n) O(n)
Min / max O(log n) O(n)
In-order traversal O(n) O(n)

Traversals take O(n) time and O(h) extra space for recursion, where h is the height.

Traversal orders

Order Visit sequence Typical use
Pre-order node, left, right Copy or serialise a tree
In-order left, node, right Sorted output from a BST
Post-order left, right, node Delete a tree, compute subtree results
Level-order level by level (BFS) Shortest depth, views by level
from collections import deque

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val, self.left, self.right = val, left, right

#        4
#      /   \
#     2     6
#    / \   / \
#   1   3 5   7
root = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)),
                   TreeNode(6, TreeNode(5), TreeNode(7)))

def inorder_iterative(node):
    out, stack = [], []
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        out.append(node.val)
        node = node.right
    return out

def level_order(node):
    if not node:
        return []
    out, q = [], deque([node])
    while q:
        level = []
        for _ in range(len(q)):
            n = q.popleft()
            level.append(n.val)
            if n.left: q.append(n.left)
            if n.right: q.append(n.right)
        out.append(level)
    return out

def height(node):
    return 0 if node is None else 1 + max(height(node.left), height(node.right))

def is_valid_bst(node, lo=float("-inf"), hi=float("inf")):
    if node is None:
        return True
    if not (lo < node.val < hi):
        return False
    return is_valid_bst(node.left, lo, node.val) and is_valid_bst(node.right, node.val, hi)

def lca_bst(node, p, q):
    while node:
        if p < node.val and q < node.val:
            node = node.left
        elif p > node.val and q > node.val:
            node = node.right
        else:
            return node.val

assert inorder_iterative(root) == [1, 2, 3, 4, 5, 6, 7]
assert level_order(root) == [[4], [2, 6], [1, 3, 5, 7]]
assert height(root) == 3
assert is_valid_bst(root)
assert lca_bst(root, 1, 3) == 2 and lca_bst(root, 3, 5) == 4

Trie (prefix tree)

A trie stores strings character by character. Insert and search cost O(L) for a word of length L, independent of how many words are stored. Use it for autocomplete, prefix search and word games.

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

    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True  # end-of-word marker

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

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

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

t = Trie()
for w in ["car", "cart", "dog"]:
    t.insert(w)
assert t.search("car") and not t.search("ca") and t.starts_with("ca")

7. Heaps and Priority Queues

A binary heap is a complete binary tree stored in an array. In a min-heap every parent is <= its children, so the minimum is at index 0. For index i: children at 2i + 1 and 2i + 2, parent at (i - 1) // 2.

Operation Cost
Peek min O(1)
Push O(log n)
Pop min O(log n)
Build heap from n items (heapify) O(n)
Search for an arbitrary value O(n)

Python’s heapq is a min-heap on a plain list. For a max-heap, push negated numbers (or (-priority, item) tuples).

Common heap patterns

import heapq

def k_largest(nums, k):
    heap = []
    for x in nums:
        heapq.heappush(heap, x)
        if len(heap) > k:
            heapq.heappop(heap)
    return sorted(heap, reverse=True)

assert k_largest([3, 1, 5, 12, 2, 11], 3) == [12, 11, 5]

def merge_k_sorted(lists):
    heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
    heapq.heapify(heap)
    out = []
    while heap:
        val, i, j = heapq.heappop(heap)
        out.append(val)
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    return out

assert merge_k_sorted([[1, 4, 7], [2, 5], [3, 6, 9]]) == [1, 2, 3, 4, 5, 6, 7, 9]

class RunningMedian:
    def __init__(self):
        self.low = []   # max-heap via negation
        self.high = []  # min-heap

    def add(self, x):
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2

rm = RunningMedian()
for x, expected in [(5, 5), (15, 10.0), (1, 5), (3, 4.0)]:
    rm.add(x)
    assert rm.median() == expected

8. Graphs

Representations

Representation Space Check edge (u, v) Iterate neighbours of u Best for
Adjacency list O(V + E) O(deg u) O(deg u) Sparse graphs (most interview problems)
Adjacency matrix O(V^2) O(1) O(V) Dense graphs, quick edge checks
Edge list O(E) O(E) O(E) Kruskal’s MST, Bellman-Ford

Grids are graphs too: each cell is a node with up to 4 (or 8) neighbours.

Algorithms

Problem Algorithm Time
Traverse / connected components BFS or DFS O(V + E)
Shortest path, unweighted BFS O(V + E)
Shortest path, non-negative weights Dijkstra with a binary heap O((V + E) log V)
Shortest path, negative weights allowed Bellman-Ford (also detects negative cycles) O(V * E)
All-pairs shortest paths Floyd-Warshall O(V^3)
Order tasks with dependencies (DAG) Topological sort (Kahn’s or DFS) O(V + E)
Cycle detection, directed DFS with colours, or Kahn’s leftover nodes O(V + E)
Cycle detection, undirected Union-find or DFS tracking the parent O(V + E)
Minimum spanning tree Kruskal (sort edges + union-find) O(E log E)
Minimum spanning tree Prim with a binary heap O(E log V)
Dynamic connectivity Union-find with path compression and union by rank ~O(alpha(n)) per op, effectively constant
Bipartite check BFS/DFS 2-colouring O(V + E)
import heapq
from collections import deque, defaultdict

# BFS shortest path on a grid ('#' is a wall). Returns steps or -1.
def grid_shortest_path(grid, start, goal):
    rows, cols = len(grid), len(grid[0])
    q = deque([(start, 0)])
    seen = {start}
    while q:
        (r, c), d = q.popleft()
        if (r, c) == goal:
            return d
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != "#" and (nr, nc) not in seen:
                seen.add((nr, nc))
                q.append(((nr, nc), d + 1))
    return -1

grid = ["..#",
        ".##",
        "..."]
assert grid_shortest_path(grid, (0, 0), (2, 2)) == 4

# Iterative DFS: count connected components.
def count_components(n, edges):
    adj = defaultdict(list)
    for u, v in edges:
        adj[u].append(v)
        adj[v].append(u)
    seen, comps = set(), 0
    for s in range(n):
        if s in seen:
            continue
        comps += 1
        stack = [s]
        seen.add(s)
        while stack:
            u = stack.pop()
            for v in adj[u]:
                if v not in seen:
                    seen.add(v)
                    stack.append(v)
    return comps

assert count_components(5, [(0, 1), (1, 2), (3, 4)]) == 2

# Kahn's topological sort. Returns [] if there is a cycle.
def topo_sort(n, edges):
    adj = defaultdict(list)
    indeg = [0] * n
    for u, v in edges:  # u must come before v
        adj[u].append(v)
        indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []

assert topo_sort(4, [(0, 1), (0, 2), (1, 3), (2, 3)]) in ([0, 1, 2, 3], [0, 2, 1, 3])
assert topo_sort(2, [(0, 1), (1, 0)]) == []

# Dijkstra: shortest distances from src, non-negative weights.
def dijkstra(n, edges, src):
    adj = defaultdict(list)
    for u, v, w in edges:
        adj[u].append((v, w))
    dist = [float("inf")] * n
    dist[src] = 0
    heap = [(0, src)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue  # stale entry
        for v, w in adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(heap, (dist[v], v))
    return dist

assert dijkstra(4, [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1)], 0) == [0, 3, 1, 4]

# Union-find with path compression and union by rank.
class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        return True

# Kruskal's minimum spanning tree weight.
def mst_weight(n, edges):
    dsu, total = DSU(n), 0
    for w, u, v in sorted(edges):
        if dsu.union(u, v):
            total += w
    return total

assert mst_weight(4, [(1, 0, 1), (4, 0, 2), (3, 1, 2), (2, 2, 3), (5, 1, 3)]) == 6

9. Sorting and Searching

Sorting algorithms

Algorithm Best Average Worst Extra space Stable
Bubble sort O(n) O(n^2) O(n^2) O(1) Yes
Insertion sort O(n) O(n^2) O(n^2) O(1) Yes
Selection sort O(n^2) O(n^2) O(n^2) O(1) No
Merge sort O(n log n) O(n log n) O(n log n) O(n) Yes
Quicksort O(n log n) O(n log n) O(n^2) O(log n) stack (average) No
Heap sort O(n log n) O(n log n) O(n log n) O(1) No
Counting sort O(n + k) O(n + k) O(n + k) O(n + k) Yes
Radix sort (d digits) O(d(n + k)) O(d(n + k)) O(d(n + k)) O(n + k) Yes
Timsort (Python sorted, Java objects) O(n) O(n log n) O(n log n) O(n) Yes

Works on any monotonic condition: once it becomes true it stays true. This includes “search on the answer” problems (minimum capacity, minimum speed, and so on).

import bisect

# bisect_left: first index where x could be inserted keeping order (first >= x).
# bisect_right: first index after any existing x (first > x).
a = [1, 2, 2, 2, 5]
assert bisect.bisect_left(a, 2) == 1
assert bisect.bisect_right(a, 2) == 4
assert bisect.bisect_right(a, 2) - bisect.bisect_left(a, 2) == 3  # count of 2s

# Generic "first value where predicate becomes True" on integers [lo, hi].
def first_true(lo, hi, pred):
    while lo < hi:
        mid = (lo + hi) // 2
        if pred(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

# Example: smallest ship capacity to ship weights within `days` days.
def ship_within_days(weights, days):
    def can(cap):
        need, load = 1, 0
        for w in weights:
            if load + w > cap:
                need, load = need + 1, 0
            load += w
        return need <= days
    return first_true(max(weights), sum(weights), can)

assert ship_within_days([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) == 15

# Merge sort.
def merge_sort(xs):
    if len(xs) <= 1:
        return xs
    mid = len(xs) // 2
    left, right = merge_sort(xs[:mid]), merge_sort(xs[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

# Quickselect: k-th smallest (0-based) in average O(n).
import random

def quickselect(xs, k):
    pivot = random.choice(xs)
    lows = [x for x in xs if x < pivot]
    pivots = [x for x in xs if x == pivot]
    highs = [x for x in xs if x > pivot]
    if k < len(lows):
        return quickselect(lows, k)
    if k < len(lows) + len(pivots):
        return pivot
    return quickselect(highs, k - len(lows) - len(pivots))

data = [9, 4, 7, 1, 8, 2, 2]
assert merge_sort(data) == sorted(data)
assert quickselect(data, 3) == sorted(data)[3]

# Sort by multiple keys: descending score, then ascending name.
people = [("bo", 90), ("al", 90), ("cy", 70)]
assert sorted(people, key=lambda p: (-p[1], p[0])) == [("al", 90), ("bo", 90), ("cy", 70)]

10. Dynamic Programming

Dynamic programming (DP) applies when a problem has optimal substructure (the answer is built from answers to subproblems) and overlapping subproblems (the same subproblem appears many times).

A five-step recipe

  1. Define the state: what does dp[i] (or dp[i][j]) mean, in one sentence?
  2. Write the transition: how does a state depend on smaller states?
  3. Set base cases.
  4. Choose the order: top-down (recursion + memo) or bottom-up (loops in dependency order).
  5. Read the answer and, if needed, reduce space by keeping only the rows you still use.

Time is roughly (number of states) x (work per transition).

Common DP families

Family Examples State
1D linear Climbing stairs, house robber, decode ways dp[i] = best answer for prefix of length i
Knapsack 0/1 knapsack, partition equal subset sum, coin change dp[capacity]
Two sequences Longest common subsequence, edit distance dp[i][j] over prefixes of both
Intervals Burst balloons, matrix chain multiplication, palindrome partitioning dp[l][r]
Grid Unique paths, minimum path sum dp[r][c]
Subsequence Longest increasing subsequence dp[i] ending at i, or patience sorting
Bitmask Travelling salesman on small n dp[mask][last]
Trees House robber III, tree diameter value returned per subtree
from functools import lru_cache
import bisect

# Top-down with memoisation.
@lru_cache(maxsize=None)
def climb(n):  # ways to climb n steps taking 1 or 2 at a time
    return 1 if n <= 1 else climb(n - 1) + climb(n - 2)

assert climb(10) == 89

# Coin change: fewest coins to make amount, or -1. O(amount * len(coins)).
def coin_change(coins, amount):
    INF = amount + 1
    dp = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a:
                dp[a] = min(dp[a], dp[a - c] + 1)
    return dp[amount] if dp[amount] != INF else -1

assert coin_change([1, 2, 5], 11) == 3
assert coin_change([2], 3) == -1

# 0/1 knapsack with a 1D array: iterate capacity downwards so each item is used once.
def knapsack(weights, values, capacity):
    dp = [0] * (capacity + 1)
    for w, v in zip(weights, values):
        for c in range(capacity, w - 1, -1):
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[capacity]

assert knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7) == 9

# Longest common subsequence, O(n * m).
def lcs(a, b):
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[-1][-1]

assert lcs("abcde", "ace") == 3

# Edit distance (Levenshtein) with two rows of memory.
def edit_distance(a, b):
    prev = list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1])
        prev = cur
    return prev[-1]

assert edit_distance("horse", "ros") == 3
assert edit_distance("", "abc") == 3

# Longest strictly increasing subsequence in O(n log n).
def lis_length(nums):
    tails = []  # tails[k] = smallest tail of an increasing subsequence of length k+1
    for x in nums:
        i = bisect.bisect_left(tails, x)
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)

assert lis_length([10, 9, 2, 5, 3, 7, 101, 18]) == 4

# House robber: no two adjacent houses.
def rob(nums):
    take = skip = 0
    for x in nums:
        take, skip = skip + x, max(take, skip)
    return max(take, skip)

assert rob([2, 7, 9, 3, 1]) == 12

11. Backtracking

Backtracking builds a solution step by step and undoes a step (“backtracks”) when it cannot lead to a valid answer. Use it to generate all subsets, permutations or combinations, and for constraint puzzles (N-Queens, Sudoku, word search).

Problem Number of results Time
Subsets of n items 2^n O(n * 2^n)
Permutations of n items n! O(n * n!)
Combinations, choose k of n C(n, k) O(k * C(n, k))

Template: choose, explore, un-choose. Prune early: skip branches that already break a constraint.

def subsets(nums):
    out, path = [], []
    def go(i):
        if i == len(nums):
            out.append(path[:])
            return
        go(i + 1)              # skip nums[i]
        path.append(nums[i])   # choose
        go(i + 1)              # explore
        path.pop()             # un-choose
    go(0)
    return out

def permutations(nums):
    out, path, used = [], [], [False] * len(nums)
    def go():
        if len(path) == len(nums):
            out.append(path[:])
            return
        for i, x in enumerate(nums):
            if not used[i]:
                used[i] = True; path.append(x)
                go()
                used[i] = False; path.pop()
    go()
    return out

def combination_sum(candidates, target):
    # each candidate may be reused; results are combinations, not orderings
    out, path = [], []
    candidates = sorted(candidates)
    def go(start, remaining):
        if remaining == 0:
            out.append(path[:])
            return
        for i in range(start, len(candidates)):
            c = candidates[i]
            if c > remaining:
                break  # prune: the rest are larger
            path.append(c)
            go(i, remaining - c)
            path.pop()
    go(0, target)
    return out

def n_queens(n):
    count = 0
    cols, d1, d2 = set(), set(), set()
    def go(r):
        nonlocal count
        if r == n:
            count += 1
            return
        for c in range(n):
            if c in cols or r - c in d1 or r + c in d2:
                continue
            cols.add(c); d1.add(r - c); d2.add(r + c)
            go(r + 1)
            cols.remove(c); d1.remove(r - c); d2.remove(r + c)
    go(0)
    return count

assert len(subsets([1, 2, 3])) == 8
assert len(permutations([1, 2, 3])) == 6
assert combination_sum([2, 3, 6, 7], 7) == [[2, 2, 3], [7]]
assert n_queens(8) == 92

12. Bit Manipulation

Operators (Python)

Operator Meaning Example
a & b AND 0b1100 & 0b1010 == 0b1000
a \| b OR 0b1100 \| 0b1010 == 0b1110
a ^ b XOR 0b1100 ^ 0b1010 == 0b0110
~a NOT (equals -a - 1 for Python ints) ~5 == -6
a << k Shift left (multiply by 2^k) 3 << 2 == 12
a >> k Arithmetic shift right (floor divide by 2^k) 13 >> 2 == 3, -1 >> 5 == -1

Tricks

Goal Expression
Is bit k set? (x >> k) & 1
Set bit k x \| (1 << k)
Clear bit k x & ~(1 << k)
Toggle bit k x ^ (1 << k)
Clear the lowest set bit x & (x - 1)
Isolate the lowest set bit x & -x
Is x a power of two (x > 0)? x & (x - 1) == 0
Count set bits bin(x).count("1"), or x.bit_count() on Python 3.10+
Number of bits needed x.bit_length()
Odd or even x & 1
XOR facts a ^ a == 0, a ^ 0 == a, XOR is commutative and associative

Python integers are arbitrary precision, so there is no overflow. To emulate 32-bit unsigned values, mask with & 0xFFFFFFFF. To read a 32-bit value as signed: x - (1 << 32) if x >= 1 << 31 else x.

# The number that appears once when every other appears twice.
from functools import reduce
from operator import xor

def single_number(nums):
    return reduce(xor, nums, 0)

assert single_number([4, 1, 2, 1, 2]) == 4

# Count bits for 0..n in O(n) using dp[i] = dp[i >> 1] + (i & 1).
def count_bits(n):
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        dp[i] = dp[i >> 1] + (i & 1)
    return dp

assert count_bits(5) == [0, 1, 1, 2, 1, 2]

# Missing number from 0..n.
def missing_number(nums):
    result = len(nums)
    for i, x in enumerate(nums):
        result ^= i ^ x
    return result

assert missing_number([3, 0, 1]) == 2

# Enumerate all subsets of n items with bitmasks.
def subsets_bitmask(items):
    n = len(items)
    return [[items[i] for i in range(n) if mask >> i & 1] for mask in range(1 << n)]

assert len(subsets_bitmask(["a", "b", "c"])) == 8

# Reverse the bits of a 32-bit unsigned integer.
def reverse_bits32(x):
    out = 0
    for _ in range(32):
        out = (out << 1) | (x & 1)
        x >>= 1
    return out

assert reverse_bits32(1) == 1 << 31
assert 12 & (12 - 1) == 8 and 12 & -12 == 4

13. Operating Systems

Processes and threads

  Process Thread
Memory Own address space Shares the address space of its process
Creation cost Higher Lower
Communication IPC: pipes, sockets, shared memory, message queues Shared variables (needs synchronisation)
Crash isolation A crash usually does not affect other processes A crash can take down the whole process
Context switch More expensive (address space change, TLB effects) Cheaper

CPU scheduling

Algorithm Idea Trade-off
First-come, first-served Run in arrival order Short jobs wait behind long ones (convoy effect)
Shortest job first Run the shortest next Good average wait; needs length estimates; can starve long jobs
Round robin Each task gets a time slice in turn Fair and responsive; overhead if slices are tiny
Priority Highest priority first Starvation; fixed by ageing
Multilevel feedback queue Several queues; tasks move between them by behaviour Adapts to interactive vs CPU-bound work

Linux has used the Completely Fair Scheduler for normal tasks for many years and moved to the EEVDF scheduler in kernel 6.6.

Memory

Deadlock

Four conditions must all hold (Coffman conditions):

  1. Mutual exclusion: a resource can be held by only one task.
  2. Hold and wait: a task holds one resource while waiting for another.
  3. No preemption: resources cannot be forcibly taken.
  4. Circular wait: a cycle of tasks each waiting on the next.

Break any one to prevent deadlock. The most practical: always acquire locks in a global fixed order (breaks circular wait), or use timeouts.

Useful Linux commands

Command Purpose
ps aux List all processes
top or htop Live CPU and memory use per process
kill PID / kill -9 PID Send SIGTERM (polite) / SIGKILL (cannot be caught)
lsof -i :8080 Which process is using port 8080
free -h Memory and swap usage (Linux)
vmstat 1 Memory, swap, I/O and CPU every second
df -h / du -sh dir Disk free per filesystem / size of a directory
strace -p PID Trace system calls of a running process (Linux)
ulimit -n Max open file descriptors for the shell
nice / renice Start or change process scheduling priority

Other terms worth knowing


14. Networking

Layers

TCP/IP layer OSI layers Examples Unit
Application 7 Application, 6 Presentation, 5 Session HTTP, DNS, TLS, SSH, SMTP Message
Transport 4 Transport TCP, UDP, QUIC (runs over UDP) Segment / datagram
Internet 3 Network IP, ICMP Packet
Link 2 Data link, 1 Physical Ethernet, Wi-Fi, ARP Frame

TCP vs UDP

  TCP UDP
Connection Connection-oriented (handshake) Connectionless
Reliability Retransmits lost data, in-order delivery No guarantees
Flow / congestion control Yes No (application must handle it)
Overhead Higher Lower
Typical uses Web, APIs, databases, file transfer DNS queries, video calls, games, QUIC

TCP three-way handshake: client sends SYN, server replies SYN-ACK, client sends ACK. Connection teardown normally uses FIN and ACK in each direction. After closing, the side that closed first waits in TIME_WAIT before the port pair can be reused.

What happens when you type a URL and press Enter

  1. The browser parses the URL and checks its caches.
  2. DNS resolves the hostname to an IP address (browser cache, OS cache, resolver, then root, TLD and authoritative servers if needed).
  3. A TCP connection is opened (or a QUIC connection over UDP for HTTP/3).
  4. A TLS handshake authenticates the server’s certificate and agrees on keys. TLS 1.3 needs one round trip for a full handshake.
  5. The browser sends an HTTP request; the server (often behind a load balancer and CDN) responds.
  6. The browser parses HTML, fetches CSS, JavaScript and images, builds the DOM and renders the page.

HTTP versions

Version Transport Key feature
HTTP/1.1 TCP Persistent connections; one request at a time per connection
HTTP/2 TCP Binary framing; many requests multiplexed over one connection; header compression
HTTP/3 QUIC over UDP Multiplexing without TCP head-of-line blocking; faster connection setup

HTTP methods and status codes

Method Safe Idempotent Typical use
GET Yes Yes Read
HEAD Yes Yes Read headers only
POST No No Create, or trigger an action
PUT No Yes Replace a resource
PATCH No Not necessarily Partial update
DELETE No Yes Delete
Code Meaning
200 OK Success
201 Created Resource created
204 No Content Success, no body
301 Moved Permanently / 308 Permanent Redirect Permanent redirect (308 keeps the method)
302 Found / 307 Temporary Redirect Temporary redirect (307 keeps the method)
304 Not Modified Cached copy is still valid
400 Bad Request Malformed request
401 Unauthorized Not authenticated
403 Forbidden Authenticated but not allowed
404 Not Found No such resource
409 Conflict Conflicts with current state
429 Too Many Requests Rate limited
500 Internal Server Error Generic server failure
502 Bad Gateway Upstream returned an invalid response
503 Service Unavailable Overloaded or down for maintenance
504 Gateway Timeout Upstream did not respond in time

Well-known ports

Port Service
22 SSH
25 SMTP
53 DNS
80 HTTP
443 HTTPS (and HTTP/3 over UDP)
3306 MySQL
5432 PostgreSQL
6379 Redis
27017 MongoDB

DNS record types

Record Maps
A Name to IPv4 address
AAAA Name to IPv6 address
CNAME Name to another name (alias)
MX Domain to mail servers
TXT Arbitrary text (SPF, verification)
NS Domain to its authoritative name servers

Addressing quick facts

Commands

Command Purpose
ping host Reachability and round-trip time (ICMP)
traceroute host Hops along the path
dig example.com / dig +short example.com AAAA DNS lookup
curl -v https://example.com Full HTTP request and response details, including TLS
curl -I https://example.com Response headers only
ss -tlnp (Linux) Listening TCP sockets and their processes
nc -zv host 443 Check whether a TCP port is open
openssl s_client -connect host:443 Inspect a TLS handshake and certificate
# Parse a URL and compute CIDR sizes with the standard library.
from urllib.parse import urlparse, parse_qs
import ipaddress

u = urlparse("https://api.example.com:8443/v1/items?id=7&sort=asc#top")
assert (u.scheme, u.hostname, u.port, u.path) == ("https", "api.example.com", 8443, "/v1/items")
assert parse_qs(u.query) == {"id": ["7"], "sort": ["asc"]}

net = ipaddress.ip_network("192.168.1.0/24")
assert net.num_addresses == 256
assert ipaddress.ip_address("192.168.1.42") in net
assert ipaddress.ip_address("10.1.2.3").is_private

15. Databases

ACID

Property Meaning
Atomicity A transaction applies completely or not at all
Consistency A transaction moves the database from one valid state to another (constraints hold)
Isolation Concurrent transactions do not see each other’s partial work (to a chosen degree)
Durability Once committed, data survives crashes (usually via a write-ahead log)

Isolation levels (SQL standard) and the anomalies they prevent

Level Dirty read Non-repeatable read Phantom read
Read uncommitted Possible Possible Possible
Read committed Prevented Possible Possible
Repeatable read Prevented Prevented Possible (by the standard)
Serializable Prevented Prevented Prevented

Real databases differ from the standard table. PostgreSQL’s default is read committed; its repeatable read is snapshot-based, prevents phantom reads, but still allows serialization anomalies such as write skew (only serializable prevents those). MySQL’s InnoDB engine defaults to repeatable read. Always check your database’s documentation.

Indexes

Normal forms (short version)

Form Rule
1NF Atomic values; no repeating groups
2NF 1NF, and every non-key column depends on the whole primary key
3NF 2NF, and non-key columns do not depend on other non-key columns
BCNF Every determinant is a candidate key

Denormalise deliberately for read performance, and accept the cost of keeping copies in sync.

SQL joins

Join Returns
INNER JOIN Rows with a match in both tables
LEFT JOIN All rows from the left table, matched rows from the right (NULL if none)
RIGHT JOIN All rows from the right table, matched from the left
FULL OUTER JOIN All rows from both, NULLs where no match
CROSS JOIN Every combination (Cartesian product)

SQL clause logical order of evaluation: FROM/JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. This is why a column alias from SELECT is not available in WHERE.

# Runnable SQL practice with the standard-library sqlite3 module.
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, amount REAL);
INSERT INTO users VALUES (1, 'ana'), (2, 'ben'), (3, 'cai');
INSERT INTO orders VALUES (1, 1, 30), (2, 1, 20), (3, 2, 5);
CREATE INDEX idx_orders_user ON orders(user_id);
""")

# LEFT JOIN + GROUP BY + HAVING: users with total spend, including users with none.
rows = db.execute("""
    SELECT u.name, COALESCE(SUM(o.amount), 0) AS total
    FROM users u LEFT JOIN orders o ON o.user_id = u.id
    GROUP BY u.id
    ORDER BY total DESC
""").fetchall()
assert rows == [("ana", 50.0), ("ben", 5.0), ("cai", 0)]

# Window function: rank orders by amount within each user.
ranked = db.execute("""
    SELECT user_id, amount, RANK() OVER (PARTITION BY user_id ORDER BY amount DESC) AS r
    FROM orders ORDER BY user_id, r
""").fetchall()
assert ranked == [(1, 30.0, 1), (1, 20.0, 2), (2, 5.0, 1)]

# Transactions: the context manager commits on success and rolls back on an exception.
try:
    with db:
        db.execute("INSERT INTO orders VALUES (4, 3, 99)")
        raise RuntimeError("simulated failure")
except RuntimeError:
    pass
assert db.execute("SELECT COUNT(*) FROM orders").fetchone()[0] == 3

# EXPLAIN QUERY PLAN shows whether the index is used.
plan = db.execute("EXPLAIN QUERY PLAN SELECT * FROM orders WHERE user_id = 1").fetchall()
assert any("idx_orders_user" in str(row) for row in plan)

Scaling databases

Technique What it does Watch out for
Vertical scaling Bigger machine Hard ceiling, cost
Read replicas Copies serve reads Replication lag: reads can be stale
Caching (Redis, Memcached) Keep hot data in memory Invalidation, stampedes
Sharding / partitioning Split data across nodes by a key Hot shards, cross-shard queries and transactions, resharding
Consistent hashing Map keys to nodes so adding a node moves only a fraction of keys Uneven load without virtual nodes

CAP theorem: when a network partition happens, a distributed system must choose between consistency (every read sees the latest write) and availability (every request gets a non-error response). PACELC extends it: else (no partition), choose between latency and consistency.

SQL (relational) NoSQL (varies by type)
Fixed schema, joins, strong transactions Flexible schema or data model per type
Scales up well, scales out with effort Many designed to scale out horizontally
Good for: relational data, complex queries, money Good for: very high write volume, simple access patterns, documents, graphs, time series

NoSQL families: key-value (Redis, DynamoDB), document (MongoDB), wide-column (Cassandra), graph (Neo4j), time series.


16. Concurrency

Vocabulary

Python specifics

Tool Best for Notes
threading I/O-bound work (network, disk) In standard CPython, the Global Interpreter Lock (GIL) lets only one thread run Python bytecode at a time, so threads do not speed up CPU-bound Python code. Since CPython 3.13 there is also an optional free-threaded build with the GIL disabled; see the official free-threading HOWTO for its current status.
multiprocessing / concurrent.futures.ProcessPoolExecutor CPU-bound work Separate processes, separate memory; arguments must be picklable
asyncio Many concurrent I/O tasks on one thread Cooperative: a task yields only at await; never block the event loop with slow sync calls
concurrent.futures.ThreadPoolExecutor Simple parallel I/O with a pool map and submit return results/futures
queue.Queue Passing work between threads safely Thread-safe FIFO
import asyncio
import threading
import queue
from concurrent.futures import ThreadPoolExecutor

# 1. A lock makes the read-modify-write on a shared counter safe.
counter = 0
lock = threading.Lock()

def work(n):
    global counter
    for _ in range(n):
        with lock:
            counter += 1

threads = [threading.Thread(target=work, args=(10_000,)) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
assert counter == 40_000

# 2. Producer-consumer with a thread-safe queue and a sentinel to stop.
q = queue.Queue(maxsize=10)
results = []

def producer():
    for i in range(20):
        q.put(i)
    q.put(None)  # sentinel

def consumer():
    while True:
        item = q.get()
        if item is None:
            break
        results.append(item * item)

tp, tc = threading.Thread(target=producer), threading.Thread(target=consumer)
tp.start(); tc.start(); tp.join(); tc.join()
assert results == [i * i for i in range(20)]

# 3. Avoid deadlock by always acquiring locks in the same global order.
lock_a, lock_b = threading.Lock(), threading.Lock()

def transfer(first, second):
    ordered = sorted([first, second], key=id)
    with ordered[0], ordered[1]:
        pass  # move money between two accounts here

t1 = threading.Thread(target=transfer, args=(lock_a, lock_b))
t2 = threading.Thread(target=transfer, args=(lock_b, lock_a))
t1.start(); t2.start(); t1.join(); t2.join()

# 4. A semaphore limits how many tasks enter a section at once.
sem = threading.Semaphore(2)
active, peak = 0, 0
state_lock = threading.Lock()

def limited():
    global active, peak
    with sem:
        with state_lock:
            active += 1
            peak = max(peak, active)
        threading.Event().wait(0.01)
        with state_lock:
            active -= 1

with ThreadPoolExecutor(max_workers=6) as pool:
    list(pool.map(lambda _: limited(), range(6)))
assert peak <= 2

# 5. asyncio: run I/O-like tasks concurrently; total time is about the longest, not the sum.
async def fetch(i, delay):
    await asyncio.sleep(delay)
    return i

async def main():
    return await asyncio.gather(*(fetch(i, 0.01) for i in range(5)))

assert asyncio.run(main()) == [0, 1, 2, 3, 4]

Patterns to name in interviews


17. System Design Numbers

Latency: rough orders of magnitude

These are approximate orders of magnitude to support estimates, not measurements. Real values depend heavily on hardware, configuration and distance, and change over time. Use them to compare options (memory vs SSD vs network), not as exact figures.

Operation Rough latency
CPU L1 cache reference ~1 ns
Branch mispredict a few ns
L2 cache reference a few ns
Mutex lock/unlock (uncontended) tens of ns
Main memory reference ~100 ns
Compress 1 KB with a fast compressor ~1-3 us
Read 1 MB sequentially from memory ~10-100 us
SSD random read ~10-100 us
Round trip within the same data centre ~0.5 ms (hundreds of us)
Read 1 MB sequentially from SSD ~0.1-1 ms
Spinning disk seek ~5-10 ms
Read 1 MB sequentially from a spinning disk ~5-20 ms
Round trip same continent ~10-50 ms
Round trip across an ocean (e.g. US to Europe) ~70-150 ms

Takeaways: memory is roughly 1,000 times faster than a network round trip within a data centre; cross-continent round trips are expensive, so minimise sequential calls between regions; sequential reads are much faster than random reads on spinning disks.

Powers of two and sizes

Power Exact value Approx. Size name
2^10 1,024 1 thousand 1 KiB
2^20 1,048,576 1 million 1 MiB
2^30 1,073,741,824 1 billion 1 GiB
2^40 ~1.1 x 10^12 1 trillion 1 TiB
2^32 4,294,967,296 ~4.3 billion number of IPv4 addresses
2^63 - 1 9,223,372,036,854,775,807 ~9.2 x 10^18 max signed 64-bit integer

Typical sizes: a char in ASCII is 1 byte; a 32-bit int is 4 bytes; a 64-bit int or double is 8 bytes; a UUID is 16 bytes (36 characters as text).

Time

Period Seconds
1 minute 60
1 hour 3,600
1 day 86,400 (~10^5)
1 month (30 days) 2,592,000 (~2.6 x 10^6)
1 year ~31.5 million (~3 x 10^7)

Quick conversion: 1 million requests per day is about 12 requests per second on average (10^6 / 86,400 ~ 11.6). Peak traffic is often several times the average; a 2x-10x peak factor is a common assumption.

Availability (“nines”)

Availability Downtime per year Downtime per 30-day month
99% ~3.65 days ~7.2 hours
99.9% ~8.76 hours ~43.2 minutes
99.99% ~52.6 minutes ~4.3 minutes
99.999% ~5.26 minutes ~26 seconds

Two dependencies in series multiply: two services each at 99.9% give about 99.8% for a request that needs both.

Back-of-the-envelope template

  1. Users and traffic: daily active users x actions per user per day / 86,400 = average QPS. Multiply for peak.
  2. Read/write ratio: most consumer apps are read-heavy, which suggests caches and replicas.
  3. Storage: items per day x size per item x retention period. Add replication (often x3).
  4. Bandwidth: QPS x response size.
  5. Memory for cache: a common heuristic is to cache the hottest ~20% of daily read data.
# Worked estimate: a photo-sharing service.
dau = 10_000_000
uploads_per_user_per_day = 0.2
views_per_user_per_day = 50
photo_bytes = 2 * 1024**2           # 2 MiB
seconds_per_day = 86_400

write_qps = dau * uploads_per_user_per_day / seconds_per_day
read_qps = dau * views_per_user_per_day / seconds_per_day
storage_per_year_tib = dau * uploads_per_user_per_day * photo_bytes * 365 / 1024**4

assert round(write_qps) == 23
assert round(read_qps) == 5787
assert round(storage_per_year_tib) == 1392   # before replication

# Availability arithmetic.
minutes_per_year = 365 * 24 * 60
assert round(minutes_per_year * (1 - 0.9999), 1) == 52.6
assert round(0.999 * 0.999, 4) == 0.998

How to Use These Sheets


FAQ

What should I memorise for a coding interview? The complexities of common operations (Section 1), the core patterns (two pointers, sliding window, BFS/DFS, binary search, heaps, DP families) and how to code them from memory: BFS, DFS, binary search, a heap-based top-k, union-find and a basic DP table. Understand the rest well enough to derive it.

Is O(n log n) always better than O(n^2)? For large inputs, yes. For very small inputs, constants matter, which is why real sorting libraries switch to insertion sort for short runs.

What is the difference between amortized and average-case complexity? Amortized is a guarantee over a sequence of operations (for example, appends to a dynamic array average O(1) even though a resize costs O(n)). Average case is an expectation over random inputs (for example, quicksort with random pivots). Amortized makes no assumptions about the input.

Is a hash table lookup really O(1)? On average, with a good hash function and a bounded load factor. The worst case is O(n) when many keys collide.

When should I use BFS instead of DFS? BFS for shortest paths in unweighted graphs and anything “level by level”. DFS for exploring all paths, cycle detection, topological sort, and when the answer is deep in the graph. Both are O(V + E).

How do I know a problem is dynamic programming? The problem asks for a count, a minimum/maximum, or whether something is possible, and a brute-force recursion would solve the same subproblem many times. Write the recursion first, then add memoisation.

Do I need to know OS, networking and databases for a coding interview? For general software engineering loops, usually only at the level of these sheets: enough to answer “what happens when you type a URL”, explain processes vs threads, and choose an index. Backend, infrastructure and systems roles go deeper.

Are these latency numbers exact? No. They are rough orders of magnitude to compare options. Hardware differs and changes over time.

Which language should I use in interviews? The one you are fastest and most accurate in. Python is popular for its short syntax and standard library, which is why the snippets here use it.

Can I use these snippets in my own projects? Yes. Content and code in this repository are MIT licensed.


Best Resources per Topic

Every link was checked in December 2026. Nothing here is sponsored. One pick per topic, with the reason it is the pick.

Topic Best pick Why this one
Big-O of common structures Big-O Cheat Sheet Long-standing single-page reference for data structure and sorting complexities.
Python operation costs Python wiki: TimeComplexity Lists the cost of list, deque, set and dict operations in CPython.
Algorithms course MIT OpenCourseWare 6.006 Introduction to Algorithms Free lectures, notes and problem sets covering most interview algorithms.
Algorithm reference cp-algorithms Clear write-ups with code for graphs, DP, strings and number theory.
Visual intuition VisuAlgo Step-by-step animations of sorting, trees, heaps, graphs and more.
Practice problems NeetCode and LeetCode Problem lists grouped by pattern, which matches how these sheets are organised.
Python standard library heapq, bisect, collections The modules interview solutions use most; the docs include recipes.
Bit manipulation Bit Twiddling Hacks Classic collection of bit tricks with explanations.
Operating systems Operating Systems: Three Easy Pieces Free, readable textbook on processes, scheduling, memory and concurrency.
Linux scheduler (EEVDF) Kernel docs: EEVDF scheduler The primary source for how current Linux schedules normal tasks.
Networking Computer Networks: A Systems Approach Free, open textbook covering the full stack.
Web performance and HTTP High Performance Browser Networking Free online book on TCP, TLS, HTTP/2 and latency from a practitioner’s view.
HTTP reference MDN HTTP docs Accurate reference for methods, headers and status codes.
SQL indexing Use The Index, Luke Free guide to how indexes really work across databases.
Isolation levels PostgreSQL: Transaction Isolation and MySQL InnoDB isolation levels Primary sources; shows how real databases differ from the SQL standard.
Database internals CMU 15-445 Database Systems University course on storage, indexing, transactions and recovery.
Concurrency The Little Book of Semaphores Free book of synchronisation puzzles with solutions.
Python concurrency threading, asyncio, free-threading HOWTO Official docs, including the current state of the GIL-free build.
System design system-design-primer Widely used free guide to scalability concepts and design questions.
Data systems in depth Designing Data-Intensive Applications The standard book on replication, partitioning, consistency and storage engines.

Where to Go Next

  1. Run the snippets: python3 tests/run_snippets.py, then break one on purpose and watch the assert catch it.
  2. Pick one pattern table (for example, sliding window) and solve three practice problems with it before moving on.
  3. Re-derive the complexities in Section 1 for one structure you use daily.
  4. For the behavioral round, pair this with a behavioral interview guide, and for design rounds, a system design guide. The Top 100 Open Source list collects free ones.

Contributing

Pull requests are welcome: fixes, clearer explanations, new sheets and more snippets. Please keep it accurate: every complexity must be correct, every command must work as written, and every Python snippet must run on a current Python 3 with only the standard library and include asserts. Run python3 tests/run_snippets.py before opening a PR.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.