DSA and Big-O Cheat Sheet

Big-O complexities of data structures and algorithms, the interview pattern finder (which pattern for which problem) and Python templates for binary search, BFS, DFS, sliding window and DP. Printable.

Big-O from fastest to slowest#

Big-ONamen = 1,000,000Example
O(1)constant1dict lookup, array index
O(log n)logarithmic~20binary search
O(n)linear1Mone loop
O(n log n)linearithmic~20Mgood sorting
O(n²)quadratic10¹² ❌nested loops
O(2ⁿ)exponential∞ ❌all subsets
O(n!)factorial∞ ❌all permutations

Rule of thumb: about 10⁸ simple operations per second. n ≤ 10⁵ needs O(n log n) or better.

Data structure costs#

StructureAccessSearchInsertDelete
Array / listO(1)O(n)O(n) (end: O(1))O(n)
Hash map / set–O(1) avgO(1) avgO(1) avg
Linked listO(n)O(n)O(1) at nodeO(1) at node
Stack / queue (deque)–O(n)O(1)O(1)
Binary heapmin O(1)O(n)O(log n)pop O(log n)
Balanced BSTO(log n)O(log n)O(log n)O(log n)

Sorting#

AlgorithmBestAverageWorstSpaceStable
Bubble / insertionO(n)O(n²)O(n²)O(1)yes
SelectionO(n²)O(n²)O(n²)O(1)no
Merge sortO(n log n)O(n log n)O(n log n)O(n)yes
Quick sortO(n log n)O(n log n)O(n²)O(log n)no
Heap sortO(n log n)O(n log n)O(n log n)O(1)no
Timsort (Python, Java objects)O(n)O(n log n)O(n log n)O(n)yes

Which pattern?#

Problem says…Try
sorted array, find a target/boundarybinary search
pair/triple summing to a targethash map, or sort + two pointers
longest/shortest contiguous subarray or substringsliding window
range sums, subarray sum = kprefix sum (+ hash map)
max subarray sumKadane
“seen before?”, counting, groupinghash set / map
matching brackets, undo, nearest previousstack
next greater / smaller elementmonotonic stack
top k, k-th largest, merge k listsheap
linked list middle or cyclefast & slow pointers
tree depth, paths, subtree questionsDFS recursion
level by level, shortest path (unweighted)BFS
islands, flood fill, mazesgrid DFS/BFS
dependencies, orderingtopological sort
weighted shortest pathDijkstra
all combinations / permutationsbacktracking
“number of ways”, “min cost”, overlapping subproblemsdynamic programming
intervals, meetingssort + sweep / greedy

Templates (Python)#

# Binary search: first index where condition is true
lo, hi = 0, len(a)
while lo < hi:
    mid = (lo + hi) // 2
    if a[mid] >= target: hi = mid
    else: lo = mid + 1
# Sliding window: longest valid window
left = best = 0
for right, x in enumerate(s):
    add(x)
    while not valid():
        remove(s[left]); left += 1
    best = max(best, right - left + 1)
# BFS
from collections import deque
q, seen = deque([start]), {start}
while q:
    node = q.popleft()
    for nxt in graph[node]:
        if nxt not in seen:
            seen.add(nxt); q.append(nxt)
# DFS on a tree
def depth(node):
    if not node: return 0
    return 1 + max(depth(node.left), depth(node.right))
# Backtracking
def backtrack(path, choices):
    if done(path): result.append(path[:]); return
    for c in choices:
        path.append(c); backtrack(path, next_choices(c)); path.pop()
# DP (bottom-up)
dp = [0] * (n + 1); dp[0] = 1
for i in range(1, n + 1):
    dp[i] = dp[i - 1] + (dp[i - 2] if i >= 2 else 0)
# Heap: k largest
import heapq
heap = []
for x in nums:
    heapq.heappush(heap, x)
    if len(heap) > k: heapq.heappop(heap)

Interview checklist#

  1. Clarify inputs, outputs, constraints, edge cases.
  2. Walk through an example by hand.
  3. Say the brute force and its Big-O.
  4. Find the pattern; explain the better approach.
  5. Code it cleanly, talking as you go.
  6. Test with examples and edge cases (empty, one item, duplicates, negatives); state time and space.

From vitalstack.co.in · vitalstack.co.in/cheat-sheets/dsa-big-o-cheat-sheet/