Skip to main content

Coding Interview Cheat Sheet 2026: Patterns, Big O, Templates

A coding interview cheat sheet is a one-page reference for the 14 algorithmic patterns, the time complexity of common data structures, the code templates you reach for under pressure, and the edge cases new grads forget. This guide is the working version: patterns, snippets in Python and JavaScript, anti-patterns interviewers downgrade for, and a 30-day prep schedule you can actually finish.

By , Founder, InterviewChamp.AI · Last updated

23 min read

TL;DR: A coding interview cheat sheet is one page: the 14 algorithmic patterns with their trigger conditions, the time complexity of the core data structures, the two or three code templates you reach for under pressure (two pointers, BFS, DFS), and the eight edge cases new grads skip. Build it from memory in about 90 minutes, drill it for two weeks, and you walk into the LeetCode-style round on Zoom able to name the pattern out loud. That recall is what ends the search, not a 600-problem grind.

What a coding interview cheat sheet is in 2026#

A coding interview cheat sheet is a one-page reference for the 14 algorithmic patterns, the time complexity of the core data structures, the code templates you reach for under pressure, and the edge cases new grads forget. You write it yourself, by hand, and then you practice rebuilding it until you can do it in your sleep.

It isn't a list of solved problems. Think of it as the structural index you can rebuild from scratch, then pull from memory while someone watches you type.

The 2026 version differs from the 2020 version in three ways.

  • The patterns themselves are stable. Two pointers is still two pointers. BFS is still BFS.
  • Rubrics moved. Interview rubrics now grade communication and edge-case discipline more heavily than raw correctness, so the sheet has to include the script for clarifying questions, not just the algorithm code.
  • The pool changed. AI-assisted prep has flooded the new-grad market with candidates who memorized solutions without internalizing patterns. What separates you is whether you can articulate the pattern, not whether you can recall the solution.

This guide is the working version. You get the patterns, code templates in Python and JavaScript, the anti-patterns, and the script for the moment you freeze. There's also a 30-day prep schedule, the complexity table you should be able to recite in under a minute, and a glossary of terms most new grads have used a hundred times without being able to define cleanly.

I built the first version of this sheet at 2am the night before a Series B phone screen. The interviewer asked for the time complexity of inserting into the middle of a Python list. I said O(n). She nodded. I got the round. Then six more rounds went the same way. The real value of the sheet showed up in the moment after, when I realized I knew the answer because I'd written it on a page by hand the week before, not because I had read it somewhere.

The 14 patterns every coding interview tests#

About 80% of CS new-grad coding rounds map to one of these 14 patterns. Topological sort and union-find sometimes get added as a 15th and 16th. Drill the 14 first.

#PatternTrigger ("when do I use this?")Typical complexity
1Two pointersSorted array, palindrome, container, in-place modificationO(n) time
2Sliding windowSubarray or substring with size or sum constraintO(n) time
3Fast and slow pointersLinked list cycle, middle of list, finding meeting pointO(n) time
4Merge intervalsOverlapping intervals, meeting rooms, calendar problemsO(n log n) for sort
5Cyclic sortArray of n integers in range [1, n] or [0, n-1]O(n) time
6In-place linked list reversalReverse whole list, reverse sublist, reverse in groupsO(n) time
7Tree BFSShortest path in unweighted tree, level-order traversalO(n) time
8Tree DFSPath sum, tree diameter, traversal-based problemsO(n) time
9Two heapsMedian of stream, sliding-window medianO(log n) per insert
10Subsets and combinationsAll subsets, permutations, combinations, backtrackingO(2^n) or O(n!)
11Modified binary searchSorted array with rotation, search insert position, peakO(log n) time
12Top-K elementsLargest-k, smallest-k, kth-element, frequency-sortO(n log k) time
13K-way mergeMerge k sorted lists, smallest-range across k arraysO(n log k) time
14Dynamic programmingOverlapping subproblems with optimal substructurevaries, often O(n*m)

Here's the mistake new grads make: trying to memorize problem by problem. What wins the round is reading the input shape and reaching for the pattern in under two minutes. Pattern recognition is the skill everything else sits on.

The honest version of the table is that two pointers, sliding window, BFS, DFS, binary search, and DP show up in 70% of new-grad interviews. The other eight are the variations and the harder rounds. If you have one week, drill those six and skip the others.

How to read the table under pressure

When the problem lands, don't start with the solution. Start with the input and the words in the prompt, then match them to a row. A few quick reads, all pulled from the trigger column above:

  • "Sorted array" or "palindrome" points to two pointers. If it's sorted and you're searching, think modified binary search.
  • "Subarray" or "substring" with a limit on what's inside points to sliding window.
  • "Linked list" plus "cycle" or "middle" points to fast and slow pointers.
  • "Intervals," "meetings" or "calendar" points to merge intervals, which usually means sort first.
  • "Kth largest," "top k" or "most frequent" points to a heap.
  • "All subsets," "all permutations" or "every combination" points to backtracking.
  • "How many ways" or "minimum cost" with repeated smaller versions of the same question points to DP.

Say the match out loud before you write a line. "This is a substring with a constraint, so I'm thinking sliding window" takes four seconds and tells the interviewer exactly how you're reasoning.

Two pointers and sliding window: when and how#

These are two of the most-asked patterns, and honestly the easiest to mix up. Two pointers is a pattern where two indices walk an array or string and move based on a comparison condition. Sliding window is a pattern where a contiguous range expands or contracts to keep an invariant true for the elements inside it. Naming which one fits the input shape, out loud, is the move that scores.

Two pointers (opposite-end variant)

def two_sum_sorted(arr, target):
    left, right = 0, len(arr) - 1
    while left < right:
        s = arr[left] + arr[right]
        if s == target:
            return [left, right]
        elif s < target:
            left += 1
        else:
            right -= 1
    return [-1, -1]

How it works: the array is sorted, and the two pointers start at opposite ends. Each comparison decides which pointer moves. Time O(n), space O(1). Variants you'll see: container with most water, valid palindrome with skipping, and 3Sum (after sorting, with an outer loop).

Two pointers (same-direction variant)

function removeDuplicates(arr) {
  if (arr.length === 0) return 0;
  let slow = 0;
  for (let fast = 1; fast < arr.length; fast++) {
    if (arr[fast] !== arr[slow]) {
      slow++;
      arr[slow] = arr[fast];
    }
  }
  return slow + 1;
}

Both pointers move forward here. The slow pointer tracks the next write position. Variants: move zeros, remove element by value, in-place compaction. It's the same pattern with a different write rule.

Sliding window (fixed size)

def max_sum_fixed_window(arr, k):
    if len(arr) < k:
        return 0
    window_sum = sum(arr[:k])
    best = window_sum
    for i in range(k, len(arr)):
        window_sum += arr[i] - arr[i - k]
        best = max(best, window_sum)
    return best

The window size k is fixed, and you slide one position right per iteration. Variants: max average subarray, and find anagrams (with a count comparison instead of a sum).

Sliding window (variable size)

def longest_unique_substring(s):
    seen = {}
    left = 0
    best = 0
    for right, ch in enumerate(s):
        if ch in seen and seen[ch] >= left:
            left = seen[ch] + 1
        seen[ch] = right
        best = max(best, right - left + 1)
    return best

The window grows until the invariant breaks, then shrinks. Triggers: "longest substring with at most K distinct chars," "minimum window containing all chars of T," "longest substring without repeating characters." The general shape is two while loops, where the outer one expands right and the inner one contracts left until the invariant is restored. (The version above jumps left straight to the right spot with a lookup, which is a shortcut for this one problem.)

The recognition signal: any problem that says "subarray" or "substring" with a constraint on the elements inside is almost always sliding window. If the constraint is a sorted-array search, it's two pointers instead.

Binary search and backtracking templates#

Two rows from the pattern table, modified binary search and subsets and combinations, get their own short templates here, because both are easy to get almost right and then lose minutes on a boundary.

Binary search (Python)

def binary_search(arr, target):
    lo, hi = 0, len(arr) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            return mid
        if arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Sorted input is required. The two lines people break are the loop condition and the moves: lo <= hi with mid + 1 and mid - 1 go together. For the rotated-array and search-insert-position variants, the skeleton stays and only the rule for which half to keep changes. Trace it on a 3-element array before you trust it.

Backtracking (Python)

def subsets(nums):
    result = []
    path = []

    def explore(start):
        result.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])     # choose
            explore(i + 1)           # explore
            path.pop()               # unchoose

    explore(0)
    return result

This is the "choose, explore, unchoose" shape from the glossary below. Permutations and combinations reuse it with a different loop and a different stopping rule. Copy path[:] when you save it, or every saved answer ends up pointing at the same list.

BFS and DFS templates you should memorize#

This is tree and graph traversal. BFS (breadth-first search) is a traversal that visits nodes level by level using a queue, which makes it the right tool for the shortest path in an unweighted graph. DFS (depth-first search) is a traversal that follows one branch as far as it goes before backtracking, using recursion or an explicit stack, and it fits path-based problems when recursion depth is bounded.

BFS template (Python)

from collections import deque

def bfs(start, graph):
    queue = deque([start])
    visited = {start}
    while queue:
        node = queue.popleft()
        # process node
        for neighbor in graph[node]:
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

Three details matter here:

  1. Use deque, not list. List pop(0) is O(n).
  2. Mark visited when you enqueue, not when you dequeue. Otherwise you enqueue the same node multiple times.
  3. For level-order traversal, snapshot len(queue) at the start of each level and process exactly that many nodes.

BFS template with levels (Python)

def level_order(root):
    if not root:
        return []
    result = []
    queue = deque([root])
    while queue:
        level_size = len(queue)
        level = []
        for _ in range(level_size):
            node = queue.popleft()
            level.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        result.append(level)
    return result

DFS template (recursive, Python)

def dfs(node, visited, graph):
    if node in visited:
        return
    visited.add(node)
    # process node
    for neighbor in graph[node]:
        dfs(neighbor, visited, graph)

DFS template (iterative, JavaScript)

function dfs(start, graph) {
  const stack = [start];
  const visited = new Set([start]);
  while (stack.length) {
    const node = stack.pop();
    // process node
    for (const neighbor of graph.get(node) ?? []) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        stack.push(neighbor);
      }
    }
  }
}

Picking recursive or iterative DFS matters more than candidates realize. Python's default recursion limit is around 1000, so trees deeper than that crash. Use iterative DFS or call sys.setrecursionlimit() if you have a deep input. JavaScript has no enforced recursion limit, but stack overflow happens around 10000 in most browsers. For interview purposes, recursive is cleaner for tree problems and iterative is safer for graph problems.

One more signal. If the interviewer says "iterative DFS," they're testing whether you can write the explicit-stack version. If they just say "DFS," recursive is fine and shorter.

Dynamic programming: the 5 sub-patterns#

Most DP questions reduce to one of five sub-patterns. Once you can tell which one you're looking at, the recurrence pretty much falls out.

1D DP

The state depends on the previous one or two values. Examples: climbing stairs, house robber, longest increasing subsequence.

def climbing_stairs(n):
    if n <= 2:
        return n
    a, b = 1, 2
    for _ in range(3, n + 1):
        a, b = b, a + b
    return b

A space trick worth knowing: most 1D DP problems don't need the full dp array. Keep the last 2-3 values in plain variables.

2D DP

The state depends on a row and a column. Examples: unique paths, edit distance, longest common subsequence.

def lcs(s1, s2):
    m, n = len(s1), len(s2)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i-1] == s2[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[m][n]

The m+1 by n+1 table with a row of zeros and a column of zeros is the standard setup. That zero row and zero column stand for the empty-string base case.

Knapsack (0/1)

Each item is either picked or skipped. Examples: subset sum, partition equal subset sum, target sum.

def can_partition(nums):
    total = sum(nums)
    if total % 2 != 0:
        return False
    target = total // 2
    dp = [False] * (target + 1)
    dp[0] = True
    for num in nums:
        for j in range(target, num - 1, -1):
            dp[j] = dp[j] or dp[j - num]
    return dp[target]

Run the inner loop in reverse so you never use the same item twice. Forgetting the reverse iteration is the most common knapsack bug in new-grad interviews.

Longest Common Subsequence variants

LCS, edit distance, regular expression matching, wildcard matching. All of them are 2D DP with a comparison-based recurrence. The skeleton is identical to the LCS code above; only the recurrence inside the if and else branches changes per problem.

Interval DP

These are problems where the recurrence is on a range [i, j]. Examples: matrix chain multiplication, burst balloons, palindrome partitioning. The signal is that the answer depends on splitting the input at some index k and combining the left and right subproblems.

def palindrome_partition_min_cuts(s):
    n = len(s)
    is_pal = [[False] * n for _ in range(n)]
    for i in range(n):
        is_pal[i][i] = True
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            if length == 2:
                is_pal[i][j] = s[i] == s[j]
            else:
                is_pal[i][j] = s[i] == s[j] and is_pal[i+1][j-1]
    cuts = [0] * n
    for i in range(n):
        if is_pal[0][i]:
            cuts[i] = 0
        else:
            cuts[i] = min(cuts[k] + 1 for k in range(i) if is_pal[k+1][i])
    return cuts[n - 1]

Interval DP shows up in the harder FAANG rounds. Most CS new-grad screens skip it. If you have 30 hours of prep total, push it to the bottom of the list.

Graphs: representations and traversal#

The graph question in a coding interview is usually one of three: is it connected, what's the shortest path, or what's the cheapest spanning tree. How you store the graph affects everything after that.

Adjacency list (Python)

from collections import defaultdict

def build_graph(edges):
    graph = defaultdict(list)
    for u, v in edges:
        graph[u].append(v)
        graph[v].append(u)  # for undirected
    return graph

Use a defaultdict(list) so you don't have to check whether a key exists. For weighted graphs, store tuples: graph[u].append((v, weight)).

Adjacency list (JavaScript)

function buildGraph(edges) {
  const graph = new Map();
  for (const [u, v] of edges) {
    if (!graph.has(u)) graph.set(u, []);
    if (!graph.has(v)) graph.set(v, []);
    graph.get(u).push(v);
    graph.get(v).push(u);
  }
  return graph;
}

Adjacency matrix

def build_matrix(n, edges):
    matrix = [[0] * n for _ in range(n)]
    for u, v in edges:
        matrix[u][v] = 1
        matrix[v][u] = 1
    return matrix

This costs O(V^2) memory. Use it only when the graph is dense (edges close to V^2) or when you need O(1) edge-existence queries. In a coding interview it's almost always the wrong pick unless the problem hands you the matrix directly.

Edge list

edges = [(u, v, weight), ...]

An edge list is useful for Kruskal's minimum spanning tree (sort by weight, then union-find as you add). For everything else, convert to an adjacency list first.

Dijkstra's algorithm (single-source shortest path)

import heapq

def dijkstra(graph, start):
    dist = {start: 0}
    pq = [(0, start)]
    while pq:
        d, node = heapq.heappop(pq)
        if d > dist.get(node, float('inf')):
            continue
        for neighbor, weight in graph[node]:
            new_dist = d + weight
            if new_dist < dist.get(neighbor, float('inf')):
                dist[neighbor] = new_dist
                heapq.heappush(pq, (new_dist, neighbor))
    return dist

It runs in O((V+E) log V) with a binary heap and works only with non-negative weights. For negative weights, switch to Bellman-Ford. For unweighted graphs, BFS is O(V+E) and shorter to write.

So the interview rule is simple. If you're asked for a shortest path and the edges are unweighted, write BFS, not Dijkstra. Reaching for Dijkstra when BFS works is over-engineering, and that's a downgrade signal.

Time complexity quick-reference table#

Memorize this table. The interviewer will ask for the complexity of every solution, and about five seconds is an acceptable answer time.

OperationBestAverageWorstNotes
Array access by indexO(1)O(1)O(1)Contiguous memory
Array search (linear)O(1)O(n)O(n)First-match early exit
Array insert at endO(1) amortizedO(1) amortizedO(n)Resize cost amortized
Array insert at frontO(n)O(n)O(n)All elements shift
Hash map insert / get / deleteO(1)O(1)O(n)Worst on hash collision
Hash set membershipO(1)O(1)O(n)Same as hash map
Linked list access by indexO(1)O(n)O(n)Head is O(1), mid is O(n)
Linked list insert at headO(1)O(1)O(1)Just rewire pointers
BST (balanced) search / insert / deleteO(log n)O(log n)O(log n)Assuming AVL or red-black
BST (unbalanced)O(log n)O(log n)O(n)Worst is sorted insert
Heap insertO(1)O(log n)O(log n)Sift-up cost
Heap peekO(1)O(1)O(1)Root access
Heap extract-minO(log n)O(log n)O(log n)Sift-down cost
Trie insert / searchO(L)O(L)O(L)L is string length
Sorting (merge sort, heap sort)O(n log n)O(n log n)O(n log n)Stable for merge sort
Sorting (quick sort)O(n log n)O(n log n)O(n^2)Worst on bad pivot
Binary searchO(1)O(log n)O(log n)Sorted input required
BFS / DFS on graphO(V+E)O(V+E)O(V+E)Adjacency list assumed
Dijkstra (binary heap)O((V+E) log V)O((V+E) log V)O((V+E) log V)Non-negative weights

The single most-asked complexity question for CS new grads: "what is the worst case of a hash map?" The answer is O(n) because of hash collisions. Most candidates say O(1) and get marked down for not knowing the worst case.

The second most-asked: "what is the time complexity of sorting in your language's standard library?" Python's sorted() is Timsort, O(n log n). JavaScript's Array.prototype.sort is engine-dependent but O(n log n) average in V8 (Chrome and Node.js). Both are stable.

Big O growth order in one line

If you only remember one line of Big O, make it the growth order, slowest-growing first: O(1) < O(log n) < O(n) < O(n log n) < O(n^2) < O(2^n) < O(n!). The glossary below defines each one. Two habits help when you state a complexity out loud: drop constants (two passes over the array is still O(n)), and keep only the biggest term (O(n^2 + n) is just O(n^2)).

Common data structure operations (Python and JavaScript)#

This is the minimal API you need to recall under pressure: push, pop, peek, contains.

Stack

Python (use a list):

stack = []
stack.append(x)           # push
top = stack[-1]            # peek
val = stack.pop()          # pop
exists = x in stack        # O(n) contains

JavaScript (use an Array):

const stack = [];
stack.push(x);             // push
const top = stack[stack.length - 1];  // peek
const val = stack.pop();   // pop
const exists = stack.includes(x);     // O(n) contains

Queue

Python (use collections.deque):

from collections import deque
queue = deque()
queue.append(x)            # enqueue
front = queue[0]           # peek
val = queue.popleft()      # dequeue (O(1))

JavaScript (no built-in deque, so use an Array with a caveat):

const queue = [];
queue.push(x);             // enqueue
const front = queue[0];    // peek
const val = queue.shift(); // dequeue (O(n), array reindex)

That JavaScript caveat is a big deal. Array.shift() is O(n) because it reindexes the entire array. For queue-heavy problems in JavaScript, write a circular-buffer wrapper or use a linked list. This trips up new grads who treat arrays the same way across both languages.

Min-heap

Python (use heapq):

import heapq
heap = []
heapq.heappush(heap, x)            # O(log n) insert
smallest = heap[0]                  # O(1) peek
val = heapq.heappop(heap)           # O(log n) extract-min
top_k = heapq.nlargest(k, arr)      # O(n log k) top-k

Python's heapq is a min-heap. For a max-heap, negate the values on push and on pop: heapq.heappush(heap, -x) and -heapq.heappop(heap).

JavaScript (no built-in heap):

// Bare-bones min-heap. For interview prep, memorize this.
class MinHeap {
  constructor() { this.data = []; }
  push(x) {
    this.data.push(x);
    this._siftUp(this.data.length - 1);
  }
  pop() {
    const top = this.data[0];
    const last = this.data.pop();
    if (this.data.length) {
      this.data[0] = last;
      this._siftDown(0);
    }
    return top;
  }
  peek() { return this.data[0]; }
  _siftUp(i) {
    while (i > 0) {
      const p = Math.floor((i - 1) / 2);
      if (this.data[p] <= this.data[i]) break;
      [this.data[p], this.data[i]] = [this.data[i], this.data[p]];
      i = p;
    }
  }
  _siftDown(i) {
    const n = this.data.length;
    while (true) {
      const l = 2 * i + 1, r = 2 * i + 2;
      let smallest = i;
      if (l < n && this.data[l] < this.data[smallest]) smallest = l;
      if (r < n && this.data[r] < this.data[smallest]) smallest = r;
      if (smallest === i) break;
      [this.data[smallest], this.data[i]] = [this.data[i], this.data[smallest]];
      i = smallest;
    }
  }
}

If you're interviewing in JavaScript, memorize the MinHeap class. It comes up in top-K, median-of-stream, Dijkstra, and merge-K-sorted-lists problems. The lack of a built-in heap is the most-cited reason new grads switch to Python mid-prep.

Hash map

Python:

d = {}
d[key] = value                      # insert / update
val = d.get(key, default)           # safe lookup
exists = key in d                   # O(1) contains
del d[key]                           # delete
for k, v in d.items(): ...          # iterate

JavaScript:

const m = new Map();
m.set(key, value);                  // insert / update
const val = m.get(key);              // returns undefined if missing
const exists = m.has(key);           // O(1) contains
m.delete(key);                       // delete
for (const [k, v] of m) {}           // iterate

JavaScript object literals work as hash maps, but they stringify keys. Use Map instead unless you have a specific reason not to. Reaching for Map over Object is a small sign of fluency, because it shows you know the difference.

Edge cases that trip up new grads (the eight-item list)#

Before writing code, talk through these eight cases. Interviewers grade communication and edge-case discipline more heavily in 2026 rubrics than they did in 2020.

  1. Empty input. Array [], string "", null tree, empty graph. Most problem statements don't specify, so ask. The candidate who handles empty input gracefully (return early, return a sensible default) avoids an easy markdown.

  2. Single-element input. Array [x], a single-character string. Many algorithms break on the boundary between "no comparison" and "first comparison." Test on the whiteboard with one element before moving on.

  3. Duplicates allowed. "Find K elements" can mean K distinct or K including duplicates. "Two Sum" with nums = [3, 3] and target = 6 should return [0, 1]. Confirm which one they mean.

  4. Negative numbers. Many candidates write the algorithm assuming positive integers, then it breaks on [-1, -2, 3]. It's especially common in subarray-sum and maximum-product problems. The classic gotcha: maximum-product-subarray has to track both max and min because two negatives multiply to a positive.

  5. Integer overflow. It's less common in Python (arbitrary precision) but real in JavaScript (Number.MAX_SAFE_INTEGER is about 9 quadrillion) and Java (a 32-bit int overflows around 2 billion). For competitive-programming problems with large inputs, mention overflow as a risk.

  6. Off-by-one on indices. Loop bounds, especially range(n) versus range(n+1), and two-pointer movement rules. The fix: always trace the algorithm on a 3-element example by hand. That catches 90% of off-by-one bugs before you write code.

  7. The problem's stated bounds. "Array length up to 10^5" tells you O(n^2) is too slow and you need O(n log n) or O(n); O(n^2) is fine only for much smaller inputs. "Array length up to 10^9" tells you that you need a streaming or math-based approach, not a loop. Read the bounds before reaching for the algorithm.

  8. Already-sorted or reverse-sorted input. Quicksort with a bad pivot strategy degrades to O(n^2) on sorted input, and some DP solutions short-circuit. Mention this when the problem says "input may be partially sorted."

The usual new-grad mistake is discovering these cases by stumbling into wrong answers mid-coding. Instead, list them out loud during the clarifying-questions phase. The interviewer notes "candidate identified edge cases proactively" on the rubric, which is a one-bump signal on most scoring sheets.

The "I do not know but here is how I would think about it" script#

The moment you freeze is the moment you lose. This script works because it turns "I do not know" into "I am reasoning through this," and reasoning is the actual signal interviewers grade.

There are four steps. Memorize the order.

Step 1: Restate the problem in your own words. Slow down. "Let me make sure I understand. You want me to..." Half the problems that feel hard become normal once you say them back. The 10 seconds of restating buys you 10 seconds of thinking.

Step 2: Walk through a small example by hand. "Let me try this with [1, 3, 5, 7] and target 8." Use 3-5 elements and trace it on the whiteboard or in the shared editor. Working an example often surfaces the pattern on its own.

Step 3: Describe a brute-force solution and its complexity. Do this even if you know it's too slow. "The naive solution is to check every pair, which is O(n^2). That's too slow for the bounds, but let me start there and optimize." Brute force first is the senior-engineer move. The interviewer wants to see whether you can explain the slow solution before chasing the fast one.

Step 4: Ask "can I trade memory for time here" and brainstorm. Almost every speedup involves caching, hashing, or precomputation. "What if I store the seen values in a hash map as I go? That would give me O(1) lookups instead of O(n), making the total O(n)." Even if the hash-map answer turns out wrong, the question is the right one to ask.

The script works because interview rubrics in 2026 explicitly grade problem decomposition over raw correctness. A candidate who gets the wrong answer with clean reasoning often beats a candidate who gets the right answer through guesswork. I've seen this play out a hundred times. Reasoning holds up under pressure; correctness alone is brittle.

Where new grads break the script is by apologizing too much. "Sorry I do not remember this one. Sorry I am thinking out loud. Sorry, can I try a different approach?" Stop apologizing. Swap every "sorry" for "let me." It takes the same time and signals the opposite confidence.

The script only works if it's reflexive, and reflexes come from reps. Rehearsing this four-step recovery against live questions is exactly what the free plan (60 minutes a month, no card) is for. See what live practice costs, with Pro at $29 a month, and run the script until it fires without thinking.

Seven anti-patterns interviewers downgrade for in 2026#

These are the patterns I see most in mock-interview review sessions. Each one is a documented rubric downgrade at most companies that grade with a scoring sheet.

1. Silent coding. Writing code without narrating your reasoning. The interviewer can't grade what you're thinking, so even with the right answer you score lower on communication. The fix: say the next 30 seconds of intent before you write each block. "I am going to use a hash map to track seen values, then iterate once and check for the complement."

2. Jumping to code before clarifying. Reading the problem and immediately typing. Spend the first 2-3 minutes asking questions about input constraints, edge cases, and the expected output format. The candidate who clarifies signals senior-level thinking. The one who starts coding right away signals junior.

3. Skipping edge cases. Writing the happy path, getting it working, then handing back the round without ever mentioning empty inputs, single elements, or duplicates. The fix: list the edge cases out loud before coding, then mention each one again as you finish.

4. Reaching for the brute force without flagging it as such. Writing the O(n^2) nested loop without saying "this is the brute force, I know it is O(n^2), I will optimize next." The interviewer reads undeclared brute force as the only approach you can think of, not as a deliberate starting point.

5. Refusing the hint when offered. When an interviewer drops a hint, they're signaling "you are close." Take it and build on it. The candidate who insists on a wrong approach instead of using the hint signals stubbornness. The candidate who says "oh, that is a great direction, let me think about how to apply it" signals coachability, which is the same thing a manager will look for on your first project.

6. Treating the interviewer as an adversary. Defensive body language, terse answers to follow-up questions, arguing with feedback. The interviewer is grading whether they want to work with you. The candidate who treats the round as a collaboration scores higher even when the technical answer is the same.

7. Writing Java-in-Python or Python-in-Java. Initializing an empty list and appending in a loop when a comprehension would do. Using range(len(arr)) instead of enumerate(arr). Building a counter dict by hand instead of using collections.Counter. Writing a for loop in JavaScript when arr.map would be cleaner. The interviewer reads non-idiomatic code as "candidate used this language but did not learn it." Idiom fluency is the senior signal at the new-grad bar.

The honest version of the list: most candidates have at least three of these. Pick the two you do most often (for most people that's silent coding and skipping edge cases) and drill them out in your next five mock interviews. The other five tend to fix themselves once those two are gone.

30-day prep schedule (one you can finish)#

This plan is built for a CS new grad who has 2-3 hours per day and one confirmed interview in 30 days. Adjust it if your timeline differs. Most plans on the internet assume 6 hours per day, which just isn't realistic for someone working part-time or juggling other applications.

Week 1: patterns (14 days compressed to 7)

  • Day 1: two pointers + sliding window (read, write the template from memory, solve 2 problems)
  • Day 2: fast and slow pointers + in-place linked list reversal
  • Day 3: tree BFS + tree DFS
  • Day 4: merge intervals + cyclic sort
  • Day 5: two heaps + top-K elements + K-way merge
  • Day 6: modified binary search + subsets and combinations
  • Day 7: dynamic programming (drill the 5 sub-patterns)

Do two problems per pattern per day. Time-box them at 30 minutes for easy and 45 for medium. If you can't solve one inside the time box, read the solution, understand it, then redo it from scratch the next morning.

Week 2: Mediums

Work 40 medium problems across the 14 patterns. Pick them from Blind 75 or NeetCode 150 (the LeetCode 75 vs Blind 75 vs NeetCode 150 comparison helps you choose). Time-box every attempt at 45 minutes. Track which patterns are slow (over 45 minutes) and which are fast (under 30). The slow ones get the extra problems in week 4.

The goal in week 2 is pattern fluency. You should be able to read the problem, identify the pattern within 2 minutes, write the brute force in 5 minutes, and write the optimized solution in 30. Anything slower is a pattern you haven't internalized yet.

Week 3: mocks

Run 5-7 mock interviews, each 45 minutes, each with your reasoning spoken out loud. Use a peer, a paid mock-interview service, or an AI-driven mock interview tool. The first mock will feel brutal. By the fifth, the structure of "clarify, brute force, optimize, edge cases" should feel automatic. If you want a real-time partner that listens to the question and helps you rehearse saying the pattern out loud until it's your own voice, run a practice round with the live interview assistant before your fifth mock.

Here's the signal you're ready: you can do a mock without looking at the cheat sheet, get the right answer 70% of the time, and explain your reasoning the whole way through. If you hit 70% by mock 5, you're ready for the live round.

Week 4: weak spots and review

Week 4 splits into weak-pattern drills, a rebuild of the sheet, and rest.

  • Days 1-2: drill the patterns you flagged as slow in week 2.
  • Days 3-4: re-solve the 10 hardest problems from weeks 1-2 without looking at past solutions.
  • Days 5-6: one final mock interview, then rebuild the cheat sheet from memory in one sitting.
  • Day 7: rest. The day before the interview is for sleep, not study. Cramming the night before is a known anti-pattern.

The 30-day plan doesn't require 600 LeetCode problems. It needs 14 patterns plus 40 mediums plus 7 mocks, which comes to about 75 problems total. The candidate who does this plan and does the spoken-reasoning work outperforms the candidate who does 400 problems silently.

One thing I'd add: don't skip week 3. Solo grinding past problem 75 has steep diminishing returns, and the next 20% of improvement lives in mocks. Most candidates skip mocks because they feel exposed. That's the point. The exposure is the prep.

Coding interview key terms glossary#

These are terms most new grads have used a hundred times without being able to define cleanly. The interviewer will sometimes ask for a definition mid-round, so be ready.

Time complexity: how runtime grows with input size, written in Big O notation. O(1) constant, O(log n) logarithmic, O(n) linear, O(n log n) linearithmic (the sorting bar), O(n^2) quadratic, O(2^n) exponential.

Space complexity: how memory use grows with input size, in the same notation as time. An algorithm can have O(n) time and O(1) space (two pointers) or O(n) time and O(n) space (hash-map two sum). The tradeoff between the two is the most common interview discussion.

Amortized complexity: the average cost per operation over a long sequence of operations, even when single operations are sometimes expensive. Python list.append is O(1) amortized because most appends are cheap and the occasional resize is spread across many cheap operations. Hash-map insert works the same way.

Stable sort: a sort that keeps the relative order of equal elements. Python's sorted is stable (Timsort). JavaScript's Array.prototype.sort is stable in modern V8. Merge sort is stable; quick sort and heap sort are not. The interview question is "is the standard-library sort stable in your language?" Know the answer.

In-place algorithm: an algorithm that changes its input directly without allocating new memory proportional to the input size. Two-pointer remove-duplicates is in-place. Sorting a copy of the array is not. In-place algorithms have O(1) extra space.

Recurrence relation: a formula that defines the answer to a problem using the answers to smaller subproblems. It's the skeleton of every DP solution. The recurrence for Fibonacci is fib(n) = fib(n-1) + fib(n-2). The one for edit distance is more complex but follows the same idea.

Memoization: top-down DP. You cache the result of each subproblem the first time it's computed and return the cached result on later calls. In Python you'd use @functools.lru_cache or a manual dict. The alternative is bottom-up tabulation, which fills a DP table iteratively.

Greedy algorithm: an algorithm that makes the locally best choice at each step. It works only when the local best leads to the global best (the "greedy choice property"). Examples: activity selection by earliest end time, and coin change with denominations that have the greedy property. Treat greedy as wrong by default; you have to prove it works before relying on it.

Divide and conquer: a strategy that breaks the problem into smaller independent subproblems, solves each recursively, and combines the results. Examples: merge sort, quick sort, binary search, fast Fourier transform. It's distinct from DP (which has overlapping subproblems) and from greedy (which doesn't recurse).

Topological sort: an ordering of the nodes of a directed acyclic graph such that for every edge u -> v, u comes before v. It's used in dependency resolution, course scheduling, and build systems. There are two algorithms: Kahn's (BFS with in-degree counting) and the DFS-based one (post-order traversal). This is one of the patterns sometimes added as a 15th to the canonical list.

Union-find (disjoint set): a data structure that tracks elements split into disjoint sets. It has two operations: find (which set is this element in) and union (merge two sets). It's used in Kruskal's MST, connectivity problems, and dynamic connectivity. With path compression and union-by-rank, each operation is nearly O(1) amortized. This is the 16th pattern.

Backtracking: a general search technique that builds candidates one step at a time and abandons (backtracks from) any candidate that can't lead to a valid solution. It's used in subsets, permutations, N-queens, Sudoku, and word search, and it's written as recursive DFS with a "choose, explore, unchoose" pattern.

Bit manipulation: algorithms that work on the binary form of integers using bitwise operators (&, |, ^, ~, <<, >>). Common patterns: check if a bit is set, count set bits, and find the single non-duplicate in an array of pairs (XOR everything). It's less common in new-grad rounds and more common at senior levels.


About the author: Sam K. is the founder of InterviewChamp.AI, building AI interview prep for the new-grad CS market and writing about the modern interview gauntlet from the inside.

Originally published on InterviewChamp.AI

Related guides

Interview Process

Beyz AI Alternatives: 7 Tools Compared on Price

Beyz AI lists $49.99 a month, or $24.99 a month billed every 6 months. Lower or shorter-commitment alternatives include Verve AI at $16.99 a month as shown (billing period unclear), Cluely at $19.99 a month and InterviewChamp at $15 a week. Pick by billing period, free plan and refund terms, not by the per-month figure alone.

Sam K. ·

Read more →
Interview Process

Cluely Alternatives: 7 Tools Compared on Price

The best Cluely alternative depends on what you need. Verve AI's card shows $16.99 a month, InterviewChamp Pro is $15 a week, and Sensei AI is $24 a month billed yearly. Cluely itself is free on Starter and $19.99 a month on its Pro card, so compare prices before you switch.

Sam K. ·

Read more →
Interview Process

Final Round AI Alternatives: 7 Tools Compared on Price

Final Round AI's free plan has no live sessions, and Pro is listed from $25 a month. If you want to test live help before you pay, Verve AI, LockedIn AI and InterviewChamp each have a free start with no card. This page compares seven alternatives on price, free plans and refund rules.

Sam K. ·

Read more →

Frequently asked questions

What should a coding interview cheat sheet include in 2026?
Six things at a minimum. First, the 14 algorithmic patterns with one-line trigger conditions. Second, time complexity for the four core data structures (array, hash map, heap, tree). Third, code templates for the two most-asked patterns (two pointers and BFS/DFS). Fourth, the standard-library idioms in your interview language. Fifth, the edge cases that come up in almost every round (empty input, single element, duplicates, negatives). Sixth, the script for the moment when you do not know the answer. Most cheat sheets skip the last two and lose candidates the round.
What are the 14 coding interview patterns every CS new grad should know?
Two pointers, sliding window, fast and slow pointers, merge intervals, cyclic sort, in-place linked list reversal, tree BFS, tree DFS, two heaps, subsets and combinations, modified binary search, top-K elements, K-way merge, and dynamic programming. Topological sort and union-find are sometimes added as a 15th and 16th. About 80% of CS new-grad coding rounds map to one of these patterns. The skill is recognizing which pattern fits the input shape within the first two minutes of reading the problem.
What time complexity should I memorize for a coding interview?
Memorize these eight rows. Array access O(1), array search O(n), hash map access O(1) average, hash map worst case O(n), binary search tree balanced O(log n), heap insert O(log n), heap peek O(1), and sorting O(n log n). For algorithms, memorize Two Sum is O(n) with a hash map, binary search is O(log n), DFS and BFS are O(V+E), Dijkstra with a heap is O((V+E) log V), and dynamic programming is usually O(n*m) for 2D states. Most interviews ask complexity after every solution. You should answer in under five seconds.
What is a two-pointer template I can memorize for coding interviews?
Two pointers is a pattern where two indices move through an array or string under specific movement rules. The most common variants: opposite-end pointers (sorted-array two sum, palindrome check, container with most water), same-direction pointers (remove duplicates in-place), and slow-and-fast pointers (linked-list cycle detection). The template in Python is a `while` loop with `left = 0` and `right = len(arr) - 1`, advancing one or both pointers based on a comparison. The interviewer cares more about why you moved which pointer than the exact code.
What is a BFS template I can memorize for coding interviews?
BFS uses a queue (in Python, `collections.deque`) and a visited set. Initialize the queue with the start node and the visited set with the start node. While the queue is non-empty, pop the left, process the node, then iterate its neighbors and enqueue each unvisited neighbor while marking it visited. For tree level-order traversal, snapshot the queue length at the start of each iteration so you process one level at a time. BFS is the right choice when you need the shortest path in an unweighted graph or the level of a node in a tree.
What is a DFS template I can memorize for coding interviews?
DFS has two equally common forms. Recursive DFS is a function that takes the current node and a visited set, marks the node visited, then recurses on each unvisited neighbor. Iterative DFS uses an explicit stack (a Python `list` with `.append` and `.pop`) instead of recursion. Pick recursive for tree problems where the tree is bounded in depth. Pick iterative for graph problems or when recursion depth could exceed the language default (about 1000 in Python). The choice signals fluency, not correctness.
What are the dynamic programming sub-patterns I should drill for coding interviews?
Five sub-patterns cover most DP questions. 1D DP (climbing stairs, house robber, longest increasing subsequence). 2D DP (unique paths, edit distance, longest common subsequence). Knapsack (0/1 knapsack, subset sum, partition equal subset). Longest common subsequence variants (LCS, edit distance, regex matching). Interval DP (merging intervals, palindrome partitioning, burst balloons). Most CS new-grad rounds test the first three. The last two show up at FAANG senior phone screens and onsite rounds.
How do I represent a graph for a coding interview question?
Adjacency list is the default. In Python, use a `defaultdict(list)` where keys are nodes and values are lists of neighbors. In JavaScript, use a `Map` where keys are node IDs and values are arrays of neighbors. For weighted graphs, store tuples of (neighbor, weight) instead of just the neighbor. Adjacency matrix is rarely the right answer in an interview because it costs O(V^2) memory. Edge list is useful when you need to sort edges (Kruskal's MST). Mention all three when the interviewer asks about graph representation tradeoffs.
What edge cases should I check on every coding interview problem?
Eight. Empty input, single-element input, duplicates allowed or not, negative numbers, integer overflow, off-by-one on indices, the maximum and minimum bounds the problem states, and the special case of the input being already-sorted or reverse-sorted. Read these out loud while clarifying. Interviewers grade communication, and the candidate who lists edge cases before coding signals senior-level thinking. The candidate who hits the same edge cases by stumbling into a wrong answer mid-coding signals the opposite.
How do I handle a coding interview question I do not know how to solve?
Use this four-step script. One: restate the problem in your own words. Two: walk through a small example by hand on the whiteboard or shared editor. Three: describe a brute-force solution and its time complexity, even if you know it is too slow. Four: ask 'can I trade memory for time here' and brainstorm. The brute force is rarely the answer they want but it is always the right starting point. Most candidates who freeze do so because they tried to jump to the optimal solution before doing the brute force. The script saves the round.
What are the most common anti-patterns interviewers downgrade for in 2026 coding interviews?
Seven. Silent coding (not narrating your thinking). Jumping to code before clarifying. Skipping edge cases. Reaching for the brute force without flagging it as such. Refusing to use the hint when offered. Treating the interviewer like an adversary instead of a collaborator. And the most-cited one in 2026 hiring panels: writing Java-in-Python or Python-in-Java because you did not learn the idioms of the language you are interviewing in. Each one of these is a downgrade signal on most rubrics.
How long does it take to prepare for a coding interview as a CS new grad?
Three to four weeks if your CS fundamentals are solid. Six to eight if you are starting from scratch. The 30-day plan that works for most new grads: week 1 on patterns (drill the 14 patterns, one per day with two problems each), week 2 on Medium problems (40 problems across patterns, time-boxed to 45 minutes each), week 3 on mock interviews (5-7 mocks with verbalized reasoning), week 4 on review and weak-spot drills. Doing 600 problems without a pattern framework is the most common failure mode and the one I see most in candidates who feel under-prepared after months of grinding.
Are coding interview cheat sheets worth carrying into a real interview?
The act of building the cheat sheet from memory is the prep. The sheet itself is for the five minutes before the interview as a warmup. Keep it closed during the round itself, whether that is a live round on Zoom, an on-site whiteboard, or an online assessment, and follow the assessment's rules on notes. The sheet is most useful for: the morning of an OA before you start, the night before a phone screen to refresh your patterns, and the week leading up to an onsite as your structured review document.
What standard-library functions should I have memorized for Python coding interviews?
`collections.deque` (O(1) push and pop both ends), `collections.Counter` (frequency count in one line), `collections.defaultdict` (auto-initialize values), `heapq.heappush` and `heappop` (min-heap operations), `heapq.nlargest` and `nsmallest` (top-K), `bisect.bisect_left` and `bisect_right` (binary search in sorted lists), `itertools.combinations` and `permutations`, `functools.lru_cache` for memoization, and `sorted` with a `key=` lambda for custom ordering. Twelve idioms cover 90% of new-grad coding interviews in Python.
What standard-library functions should I have memorized for JavaScript coding interviews?
`Map` and `Set` (O(1) lookup), `Array.prototype.sort` (note: lexicographic by default, pass a comparator for numbers), `Array.prototype.slice` and `splice` (slice is non-mutating, splice mutates), `Array.from` and the spread operator for array conversion, `JSON.stringify` for serializing visited-set keys, and the absence of a built-in deque or priority queue (build a min-heap from scratch or use a sorted array with `splice`). The lack of a native heap is the biggest gap from Python and the one that trips up new grads switching languages mid-prep.
How do I use this coding interview cheat sheet for interview practice?
Treat the cheat sheet as the index for your interview practice, not a thing to memorize cold. Rebuild it from memory once, then spend each practice block drilling the gaps it exposes: the patterns you cannot template in under 60 seconds and the complexity rows you hesitate on. The highest-leverage coding interview practice in 2026 is timed mock rounds with verbalized reasoning, because the rubric grades how you talk through the pattern, not just whether your code runs. Use a peer, a mock-interview service, or an AI interview practice tool to get the reps under observation.
Does AI interview practice actually help for coding interviews?
It helps for the part that solo grinding cannot fix: saying the answer out loud under pressure. AI interview practice gives you unlimited timed reps where you narrate the pattern, the brute force, and the complexity, then get the question parsed back to you in real time. That builds the reflex of articulating your reasoning, which is the resilient signal in 2026 coding-interview rubrics. It does not replace doing the problems; it replaces the wall of doing them silently. The goal is walking into the live round able to talk through the solution in your own voice.