iq.lab
Python starts when a code cell comes near or you run one

Reference

Glossary

Every term the course uses, in plain words, with a link to where it is taught.

221 terms

0/1 knapsack · also knapsack, knapsack problem

Items with weights and values, and a bag that holds at most a total weight (the capacity). Each item is taken 0 times or 1 time, for the most total value. dp[i][w] is the best value from the first i items within weight w: skip item i, or take it on top of the row above. One row walked downward is enough. O(n × capacity) time.

Taught in Dynamic programming
Adjacency list

A dict from each node to the list of its neighbors, so finding a node's neighbors is one lookup. Build it from an edge list (a list of [a, b] pairs) in one pass, often with defaultdict(list): append b to the list of a, and for a two-way edge also a to the list of b. When the problem gives n, give every node a list, because a node with no edges never appears in the edge list. It takes O(n + E) space for n nodes and E edges, where an adjacency matrix (an n by n grid of yes or no) always takes n2 cells.

Taught in Graphs
Aliasing · also alias

Two names for one object. After b = a, where a names a list, b.append(4) shows up through a too, because there is only one list. For a separate copy, write a[:] or list(a).

Taught in Python, one step at a time
Amortized cost · also amortized O(1)

The average cost per operation over a long run of operations. append is amortized O(1): when a list's block of memory is full, one append copies every item into a bigger block, but the blocks grow in proportion to their size, so n appends cost O(n) in total.

Taught in Counting steps: Big O
Anagram

Two strings are anagrams when one is a rearrangement of the other: the same letters, each used the same number of times, as in "stop" and "pots". Compare letter counts to check two strings; group by the sorted letters to collect many.

Taught in Arrays and hash maps
Backtracking · also backtracking search

A way to list or search every answer that is built from a series of choices: make one choice, explore everything that follows from it, undo it, and try the next choice. It walks the choice tree depth first with one shared path. Subsets, orderings, phone-letter strings, word search and N-Queens are all backtracking.

Taught in Backtracking
Balanced binary tree · also height-balanced tree, balanced tree

A tree in which, at every node, the heights of the left and right subtrees differ by at most 1. Every node must pass, not only the root, and the rule compares sibling subtrees, not the levels of leaves. One walk checks it: each call returns its subtree's height, or -1, which no height can be, to mean out of balance somewhere below. A balanced tree's height is O(log n).

Taught in Recursion and trees
Base case

The input a recursive function answers outright, with no further calls: n <= 1 for factorial, None (the empty tree) for a tree walk. Every call must move toward a base case and must not be able to jump past it: count_down(n - 2) from an odd n skips n == 0, so test a range, n <= 0. Its value must not spoil the answer: 0 for a count or a sum, float("-inf") for a maximum.

Taught in Recursion and trees
Best case

The input of a given size n that needs the fewest steps. For a search that stops at the first match, the best case has the target in first place: 1 pass. It needs a lucky input, so it promises nothing about the next one.

Taught in Counting steps: Big O
Big O · also Big O notation

A label for a growth rate, written O(...) and read "order ...". Keep the fastest-growing term and drop constant factors: 3n + 5 is O(n), and n2/2 + n is O(n2). Precisely, O(n2) means that for large n the step count is at most some fixed number times n2, and the same goes for the other classes.

Taught in Counting steps: Big O
Binary · also base 2, binary representation

Writing numbers in base 2, with only the digits 0 and 1. Each digit is worth twice the one to its right: 1, 2, 4, 8, 16 and so on. 13 is 8 + 4 + 1, so in binary it is 1101. bin(13) gives '0b1101', and 0b1101 typed in code is the number 13.

Taught in Greedy and a little math
Binary search on the answer · also search on the answer

Binary search over a range of possible answers (a speed, a capacity, a time) instead of over a list. It needs a check, "does x work?", that switches from no to yes once as x grows. lo starts at the smallest value that could work and hi at a value that surely works. The cost is one check times about log₂ of the range size.

Taught in Sorting and binary search
Binary search tree · also BST

A binary tree that keeps one promise at every node: every value in the left subtree is smaller than the node's value, and every value in the right subtree is larger. Search and insert walk one path from the root, O(h): about log₂ n for a balanced tree, but n for a tree built from sorted input. An inorder walk meets the values in sorted order. To check one, hand each node the range (low, high) set by all of its ancestors; comparing a node only with its children is not enough.

Taught in Recursion and trees
Binary tree

A set of nodes in which each node has at most two children, a left one and a right one. You hold a tree by its root, the one node no other node points at; an empty tree is a root of None. A node with no children is a leaf. A node together with everything below it is its subtree, so every node is the root of its own subtree. The nodes the same number of steps below the root form a level.

Taught in Recursion and trees
bisect · also bisect_left, bisect_right

Python's module for the first-true search on a sorted list. bisect.bisect_left(nums, x) is the first index with nums[i] >= x, and bisect.bisect_right(nums, x) is the first index with nums[i] > x. Both return the length when no index qualifies, both cost O(log n), and their difference counts the copies of x.

Taught in Sorting and binary search
Bit · also binary digit

One binary digit: 0 or 1. x & 1 is the last bit of x, the same as x % 2, and x >> 1 drops it, the same as x // 2. A number n has about log₂ n bits: 13 has 4.

Taught in Greedy and a little math
Bit shift · also <<, >>, left shift, right shift

Moving every bit of a number sideways. x << 1 moves each bit one place left and puts a 0 on the right, which doubles x. x >> 1 moves each bit one place right and drops the last one, the same as x // 2.

Taught in Greedy and a little math
Bitwise operators · also &, |, AND, OR, bitwise AND, bitwise OR

Operators that line up the bits of two numbers and combine them one column at a time. & (AND) gives 1 where both bits are 1, | (OR) gives 1 where either bit is 1, and ^ (XOR) gives 1 where the bits differ. With 12 (1100) and 10 (1010): 12 & 10 is 8, 12 | 10 is 14 and 12 ^ 10 is 6.

Taught in Greedy and a little math
Bottom-up · also tabulation, bottom-up DP

Dynamic programming that fills a table with a loop, starting from the base cases, in an order where every cell's inputs are already filled. It computes the same answers as a memo with no recursion, so it has no depth limit, and it is the version that can shrink to the last row or the last two values.

Taught in Dynamic programming
Brute force

The plain approach that tries every possibility with no cleverness, such as comparing every pair of numbers to find a duplicate: up to n(n − 1)/2 comparisons, O(n2) time. In an interview you name it and its cost first, then improve on it.

Taught in The interview and this lab
Bucket

One of the numbered places in a hash map where keys are kept. A key lives in bucket hash(key) % len(buckets), so a lookup computes that number and searches that bucket alone.

Taught in Arrays and hash maps
Bucket sort by frequency

A way to find the most frequent values without sorting: count every value, then put each value into buckets[count], a list of n + 1 lists. Reading the buckets from n down to 1 gives the values from most to least frequent, in O(n) time on average.

Taught in Arrays and hash maps
Call stack

The calls that have started and not yet finished, kept in a pile with the newest on top. Each call gets its own frame, a box of its own names, and only the top call runs; the others wait on the line that made the call and resume when it returns. The number of frames at once is the recursion's depth, and a recursion uses O(depth) extra space for them, even when the code has no list.

Taught in Recursion and trees
Capacity · also spare room

How many slots a list's block of memory has, as opposed to its length, the number of items it holds (what len(nums) returns). The slots past the last item are spare room: an append into spare room writes one slot and moves nothing, while an append into a full list first copies every item into a bigger block. Each new block grows in proportion to the list (double, in the lesson), so most appends land in spare room, which is why append is amortized O(1).

Taught in Arrays and hash maps
Chaining · also separate chaining

A way to handle collisions: each bucket holds a short list of its keys, called its chain. A lookup compares the key with each item in one chain and nowhere else. Python's own dict and set put a colliding key in another free slot of the same table instead, with the same average and worst-case costs.

Taught in Arrays and hash maps
Choice tree · also state-space tree

A picture of every way to make a series of decisions. The root has decided nothing, each box one level down has made one more choice, and a leaf at the bottom has made every choice: the path from the root down to it is one finished answer. The subsets of n items make a tree with 2n leaves; their orderings, n! leaves.

Taught in Backtracking
Choose, explore, unchoose · also backtracking template, choose, recurse, undo

The three moves a backtracking call makes for each option it tries: choose (change the notebook, often path.append(x)), explore (call the function again to extend the path), unchoose (undo the change, often path.pop()). The undo keeps the promise that every call leaves the shared notebook as it found it, so the next option starts clean.

Taught in Backtracking
Clarifying question

A question asked before you plan, whose answer changes the code: what one item is, what to return, the odd cases (empty input, repeats, ties) and how large n gets. End the clarify phase by restating the problem in one sentence the interviewer can correct.

Taught in Interview mode
Class · also method, constructor, __init__, self

A bundle of a notebook and the functions that use it. A function inside a class is a method; module 0 first showed one in LeetCode's class Solution. Calling the class like a function, as in SlowSums(nums) from the prefix sums lesson, makes a new object and runs its __init__ method once: __init__ is the constructor. Every method receives the object as its first parameter, self, and a name stored on self, such as self.nums, stays with that one object from one call to the next.

Taught in Arrays and hash maps
Collision · also hash collision

Two different keys whose hashes pick the same bucket. With 8 buckets, hashes 641 and 625 collide, since both leave remainder 1 when divided by 8. With more possible keys than buckets, collisions cannot be avoided; the table keeps each bucket's keys together.

Taught in Arrays and hash maps
Combination

A selection of items where order does not matter: [1, 3] and [3, 1] are the same combination. To list each one once, build it in one fixed order only (sorted, or the order of the input) with a start index. In combination sum a number may be picked more than once, so [2, 2, 3] is one combination.

Taught in Backtracking
Complete tree · also complete binary tree

A tree with no gaps: every level is full before the next starts, and the last level fills from the left. A heap's tree is always complete, which is why it fits in a plain list.

Taught in Heaps and tries
Complexity class

A family of growth rates that share one Big O label. The common ones, slowest-growing first, with code that produces each: O(1) (reading nums[i]), O(log n) (halving), O(n) (one loop), O(n log n) (sorting), O(n2) (every pair), O(2n) (every subset) and O(n!) (every ordering). Out loud, people say constant, logarithmic, linear, quadratic and exponential time for O(1), O(log n), O(n), O(n2) and O(2n).

Taught in Counting steps: Big O
Conditional expression · also one-line if/else, ternary

An if/else that picks one of two values, written in one line: label = "even" if x % 2 == 0 else "odd". Python asks the test first, then works out only the chosen side. It is a value, so it fits anywhere a value can, such as return a if a > b else b. For three or more outcomes, write an if/elif/else chain.

Taught in Python, one step at a time
Connected component · also component

A group of nodes that can all reach each other, with no edge leaving the group: an island on a map, or one customer among matched accounts. Count them by starting a search at every node no earlier search reached, or with union-find, by starting at n and subtracting one for every merge. A node with no edges is a component of its own.

Taught in Graphs
Constraints · also size limit

The limits a problem states on its input, such as 1 ≤ n ≤ 105 for a list of up to 100,000 numbers. LeetCode lists them under Constraints; in an interview, you ask "how large is n?" The largest n tells you which class to aim for: at about 107 simple steps per second in Python, n up to 105 needs O(n log n) or better, n up to 1,000 allows O(n2), and n up to 20 allows O(2n).

Taught in Counting steps: Big O
Cost

How much work an algorithm does as its input grows: time (how many steps) and extra space (how big the notebook gets). One pass over n numbers that keeps a fixed handful of names (the notebook and the loop variable) costs O(n) time and O(1) extra space. Module 2 makes the notation exact. The fourth part of the frame.

Taught in The interview and this lab
Costume · also deformed problem

A familiar problem retold with a new story, new names or one changed rule. Hours until a busier hour is Daily Temperatures (LeetCode 739) with days renamed to hours and temperatures to package counts. Interviewers deform known problems, so learn the signals, not memorized solutions.

Taught in Interview mode
Counterexample

One input on which an idea gives a wrong answer. One is enough to rule out a greedy rule: the amount 6 with coins 4, 3 and 1 rules out biggest-coin-first for those coins. Look for one on tiny inputs first, because they are quick to check by hand.

Taught in Greedy and a little math
Cycle · also loop

A path that comes back to the node where it started without using any edge twice. In a dependency graph, the tasks on a cycle wait on each other forever, so no run order exists. In a search, cycles (and two-way edges) are why you keep a set of the nodes already reached.

Taught in Graphs
Deque · also double-ended queue, collections.deque

Short for double-ended queue, said "deck": collections.deque. It adds and removes at both ends in O(1) (append, pop, appendleft, popleft) because it keeps its items in a chain of small blocks and moves a marker instead of shifting items. Reading an index far from both ends is O(n).

Taught in Stacks and queues
Diagonal keys · also row - col, row + col, anti-diagonal

One number that names a whole diagonal of a grid. Along a down-right diagonal row - col stays the same; along an up-right diagonal row + col stays the same. Sets of these numbers check both diagonals of a square in O(1), as in N-Queens.

Taught in Backtracking
Diameter of a binary tree · also diameter

The number of edges on the longest path between any two nodes of a tree. The path turns at its highest node and need not pass through the root. Each call returns its subtree's height to its parent and records left + right, the longest turn at its node, in an outside variable, because a parent can extend a child's height but not a child's diameter. One walk: O(n) time, O(h) space.

Taught in Recursion and trees
Dict · also dictionary, lookup table

A lookup table from keys to values. d = {} makes an empty one, d[k] = v stores a value, d[k] reads it (a missing key raises KeyError), k in d asks whether a key is there, and d.get(k, 0) reads with 0 for a missing key. Counting is counts[w] = counts.get(w, 0) + 1. A dict is Python's hash map: a lookup takes about one step on average.

Taught in Python, one step at a time
Dijkstra's algorithm

Finds the cheapest route from one source to every node in a weighted graph (one whose edges carry numbers, such as delays), when no weight is negative. A heap of (distance, node) pairs hands out the closest node not yet settled. Its distance is final, so it is settled, and each edge out of it is relaxed: if going through it is cheaper, the neighbor's distance drops and a new pair is pushed. Pairs left behind by a drop are stale and are skipped when they come out. O((V + E) log V) time; with a negative weight, use Bellman-Ford instead.

Taught in Graphs
Directed acyclic graph · also DAG

A directed graph with no cycle. Airflow DAGs and dbt projects are directed acyclic graphs: tasks or models are the nodes and dependencies are the edges. Because there is no cycle, a topological order (an order that runs every task after the tasks it waits for) always exists.

Taught in Graphs
Directed and undirected graphs · also one-way edges, two-way edges

In a directed graph each edge goes one way and is drawn as an arrow: an edge from raw to clean lets you step from raw to clean but not back. In an undirected graph each edge goes both ways, like a friendship. In an adjacency list, a one-way edge is one append and a two-way edge is two.

Taught in Graphs
Doubly linked list

A linked list whose nodes have two pointers: next to the node after and prev to the node before. Holding a node, you reach both of its neighbors in one step, so taking it out is two pointer changes (node.prev.next = node.next and node.next.prev = node.prev), and putting it next to a node you hold is four. With next alone, finding the node before means walking from the head.

Taught in Linked lists
Downleveling · also downlevel, downleveled

An offer at a lower level than the one you interviewed for. It is common, and no trustworthy rate for it exists. Ask the recruiter about level before anything is scheduled: which level the loop (the full set of interviews for one job) is calibrated for, and at what level an offer would be written. Once the interviews are over, the level is hard to change.

Taught in The interview and this lab
Dummy head · also dummy node, placeholder node

A placeholder node made in front of a list, dummy = ListNode() or dummy = ListNode(0, head), whose value is never used. It gives the first real node a node before it, so attaching (tail.next = node, then tail = tail.next) and removing (before.next = before.next.next) work the same way at the head as anywhere else. The answer is dummy.next.

Taught in Linked lists
Dynamic programming · also DP

Solving a problem from the answers to smaller versions of itself, when the same smaller versions come up again and again, so that each one is solved once and its answer stored. The answers live in a memo filled by recursion (top-down) or in a table filled by a loop from the base cases up (bottom-up). The cost is the number of different subproblems times the work for each.

Taught in Dynamic programming
Early return

A return inside a loop that ends the call as soon as the answer is known, such as the position of the first negative number. The "not found" answer goes after the loop, because it is only known once every item has been checked.

Taught in Python, one step at a time
Edge case

An unusual input that code must still handle: an empty list, a single item, duplicates, negative numbers, or a boundary (a value right at the edge of a rule, such as a number equal to the limit, or an item in the first or last position). Raise edge cases before you are asked, and trace them before you say "done".

Taught in The interview and this lab
Edit distance · also Levenshtein distance

The fewest one-letter inserts, deletes and replaces that turn one string into another: "ear" into "are" takes 2. In the table, the cell above is a delete, the cell to the left an insert, and the cell above-left a replace (or a free match). Row 0 and column 0 start at 0, 1, 2, and so on. O(m × n) time.

Taught in Dynamic programming
End-of-word mark · also end mark, is_end

The flag on a trie node that says a stored word ends here: the key "$" in the dict-of-dicts version, is_end in the TrieNode class. A node that exists proves only that some stored word starts that way. After storing only "cart", the node for "car" exists but has no mark. search needs the mark; starts_with needs only the node.

Taught in Heaps and tries
Eviction · also evict

Removing an entry from a full cache to make room. In an LRU cache it happens only when a put brings a new key and the cache is already at capacity; an update to a key that is already there never evicts. Each node stores its key, so evicting a node can delete its dict entry too.

Taught in Linked lists
Exchange argument

The usual reason a greedy choice is safe: take any best answer, swap part of it for the greedy choice, and show that the swap never makes it worse. Then some best answer contains the greedy choice, so taking it loses nothing. For bookings: take any largest set with no clashes and swap its first-ending booking for the booking that ends first overall. That one ends no later, so the rest of the set still fits after it, and the set keeps its size.

Taught in Sorting and binary search
Factorial · also n!

n! (read "n factorial") is n × (n − 1) × ... × 2 × 1, the number of orderings of n items: 3! = 6 and 10! = 3,628,800. An algorithm that tries every ordering is O(n!), which fits a one second budget only up to about n = 10.

Taught in Counting steps: Big O
Fast and slow pointers · also slow and fast pointers, runner technique

Two names walking one linked list at different speeds: slow moves one node per step and fast moves two. When fast cannot move two more nodes, slow is at position n // 2, the middle (the second of the two middles when n is even). The loop test while fast is not None and fast.next is not None makes reading fast.next.next safe. The same pair detects a cycle.

Taught in Linked lists
First-true template

The binary search that finds the first index where a yes/no answer turns to yes, when every no comes before every yes: lo, hi = 0, len(nums), loop while lo < hi, a yes sets hi = mid, a no sets lo = mid + 1, then return lo. It returns the length when no index is a yes.

Taught in Sorting and binary search
Fixed-gap pointers

Two pointers moving at the same speed, one n nodes ahead of the other. Move fast n nodes first, then move both one node per step. When fast walks off the end, slow is node number n from the end (the last node is number 1). Starting both on a dummy head and stopping when fast is on the last node leaves slow on the node before that one, ready to remove it. One walk, O(1) extra space.

Taught in Linked lists
Fixed-size window · also fixed window

A sliding window that always holds the same number of items, k. Each slide adds the item at right and removes the item at right - k, and the window then starts at right - k + 1. A list of n items has n − k + 1 such windows. Sliding visits all of them in O(n) time, where adding each one up from scratch costs O(n·k).

Taught in Two pointers and sliding windows
Floor division · also integer division, //

a // b divides and rounds down to a whole number: 7 // 2 is 3, and -7 // 2 is -4, because rounding down moves toward the smaller number. Plain / always gives a float: 7 / 2 is 3.5 and 8 / 2 is 4.0.

Taught in Python, one step at a time
Floyd's cycle check · also tortoise and hare, Floyd's cycle detection

Finding a cycle in a linked list with fast and slow pointers and no other memory. Both start at the head; each step moves slow one node and fast two, then checks slow is fast. Without a cycle, fast reaches the end. With one, the gap from fast forward to slow shrinks by exactly one node per step once both are in the loop, so fast cannot jump over slow, and they meet. O(n) time and O(1) extra space, where a set of visited nodes costs O(n) space.

Taught in Linked lists
Follow-up types · also follow-ups, complexity probe, scale shift, constraint flip, rationale probe

The five shapes of question that come after a working answer: a complexity probe (what does it cost?), a scale shift (the input no longer fits in memory), a constraint flip (a rule about the input changes), an extension (also return or do something more) and a rationale probe (why this approach?).

Taught in The interview and this lab
Frame · also frame card, walk, notebook, promise, cost

The four questions this course answers for every algorithm: the walk (the order we visit the data), the notebook (what we write down as we go), the promise (what stays true about the notebook after every step) and the cost (time and extra space). Every pattern and problem states all four on a frame card.

Taught in The interview and this lab
functools.cache · also @cache, cache decorator

A decorator from the functools module. Written as @cache on the line above a def, it wraps the function with a hidden dict from its arguments to its result, so a repeated call returns the saved result without running the body. Every argument must be hashable: pass an index like i, not a list.

Taught in Dynamic programming
Generate and filter · also generate and test

The brute force for a search problem: build every leaf of the choice tree, then check each finished one against the rule. For balanced brackets with 2 pairs it builds 16 strings to keep 2. Name it and its cost first, then improve it with pruning.

Taught in Backtracking
Generator expression · also genexp

A comprehension inside a call, without its square brackets: any(x < 0 for x in nums) or sum(x * x for x in nums). It makes the values one at a time, as the call asks for them, so any and all can stop at the first value that settles the answer, and the whole list is never built.

Taught in Python, one step at a time
Graph

A set of nodes (also called vertices) joined by edges, where each edge connects two nodes. The nodes one edge away from a node are its neighbors. A path is a chain of nodes where each step follows an edge, and a node is reachable from another when some path leads to it. Tables in a lineage graph, cells on a map and courses with prerequisites are all graphs.

Taught in Graphs
Greatest common divisor · also gcd, Euclid's algorithm, Euclidean algorithm

The largest number that divides both a and b: gcd(48, 18) is 6. Euclid's rule finds it fast: gcd(a, b) equals gcd(b, a % b), repeated until the second number is 0, and then the first number is the answer. Python has it as math.gcd.

Taught in Greedy and a little math
Greedy algorithm · also greedy, greedy choice

An algorithm that builds its answer one choice at a time, always takes the choice that looks best right now, and never goes back to change it. It is usually one pass with a number or two in the notebook. The shipping check is greedy: it keeps putting the next package on today's ship while it fits, and starts a new day only when it does not. A greedy choice is not always right, so it needs a reason. Shipping's reason: after every day, greedy is at least as far along the belt as any other loading. Another common reason is an exchange argument.

Taught in Sorting and binary search
Grid graph

A grid read as a graph: each cell (row, column) is a node, and its neighbors are the cells directly up, down, left and right (diagonals only when the problem says so). The neighbors come from a directions list of row and column changes plus a bounds check, 0 <= nr < rows and 0 <= nc < cols, made before the cell is read. Both halves matter: grid[-1] quietly reads the last row instead of failing.

Taught in Graphs
Grouping key

The value computed from each item to decide its group in a dict of lists. A good key is equal for two items exactly when they belong together, and it must be hashable: the sorted letters of a word group anagrams, and a tuple of letter counts works too.

Taught in Arrays and hash maps
Growth rate · also time complexity

How fast an algorithm's step count grows as its input grows. Big O writes it down: one loop over the list grows in step with n, O(n); comparing every pair grows with n × n, O(n2).

Taught in Counting steps: Big O
Half-open interval

An interval written [start, end) that includes its start but not its end, the usual model for a meeting: [1, 3) is over at 3, so [3, 5) can use the same room. Two half-open intervals clash only when each starts before the other ends: a[0] < b[1] and b[0] < a[1].

Taught in Sorting and binary search
Hamming distance

The number of bit positions where two numbers differ, which is the number of 1s in x ^ y. 1 (001) and 4 (100) differ in two places, so their Hamming distance is 2.

Taught in Greedy and a little math
Hash function · also hash

A rule that turns a key into a whole number, the key's hash. The same key must always give the same number. A hash map uses hash(key) % len(buckets) to pick the one bucket where the key can live. Python's built-in is hash().

Taught in Arrays and hash maps
Hash map · also hash table

A structure that finds a key without searching everything it holds: the key's hash picks one bucket, and only that bucket is searched. Python's dict and set are hash maps. A lookup or an add is O(1) on average and O(n) in the worst case, when many keys share one bucket.

Taught in Arrays and hash maps
Hashable

A value whose hash can never change, so it can be a dict key or a set item: numbers, strings, and tuples of hashable values. Lists, dicts and sets can change after they are stored, so Python refuses them as keys with a TypeError that says unhashable type: 'list' (or 'dict', or 'set'). To use a list's contents as a key, convert it first with tuple(nums).

Taught in Arrays and hash maps
Heap · also min-heap, binary heap

A list read as a tree, level by level and left to right, that keeps one promise: no parent is bigger than its children, so the smallest item is always at index 0. The children of index i are at 2 * i + 1 and 2 * i + 2, and its parent is at (i - 1) // 2. Push and pop cost O(log n); reading the smallest, heap[0], costs O(1). The rest of the list is not sorted: [1, 3, 8, 5] is a heap.

Taught in Heaps and tries
heapify · also heapq.heapify, build a heap

Turning a whole list into a heap in place: sift down every parent, from index n // 2 - 1 back to index 0. It costs O(n), less than n pushes at O(n log n), because about half the items are leaves, which it never sifts, and only the root can sink the whole height. heapq.heapify(nums) changes nums itself, so heapify a copy, list(nums), when the caller still needs the original.

Taught in Heaps and tries
heapq · also priority queue, heap queue

Python's heap module. It has no heap object: the list is the heap, and the promise holds only while every change goes through heapq. heapq.heappush(heap, x) adds x, heapq.heappop(heap) removes and returns the smallest, heapq.heapify(nums) rearranges a list into a heap, and heap[0] reads the smallest. heappush and heappop keep a min-heap. Python 3.14 added max-heap versions such as heappush_max, but older versions lack them, so negating works everywhere. A heap is the usual way to build a priority queue: a collection that always hands over its most urgent item next.

Taught in Heaps and tries
Height of a tree · also height, max depth, maximum depth

The number of levels in a tree: the number of nodes on its longest path from the root down to a leaf. An empty tree has height 0 and a single node has height 1. The height, h, decides the cost of tree walks: O(h) extra space for a recursive walk, O(h) time for a search in a binary search tree. h is about log₂ n for a balanced tree and n for a chain. Some books count edges instead, which gives one less.

Taught in Recursion and trees
Hidden loop

One line of Python that walks, shifts or copies a whole list or string, such as x in a_list, a_list.index(x), min, max, sum, insert(0, x), pop(0), a slice or s += t. Inside a loop of n passes, an O(n) line makes the function O(n2), so price every line, built-ins included.

Taught in Counting steps: Big O
Histogram

In this course, a bar chart of bars of width 1 standing side by side, where heights[i] is the height of bar i. The classic question is the largest rectangle that fits under the bars, solved with a monotonic stack that finds each bar's first shorter bar on both sides.

Taught in Stacks and queues
Identity check · also is, is not

a is b asks whether two names lead to the very same object; a == b asks whether two values are equal. Two different nodes that both hold 4 have equal values, a.val == b.val, but a is b is False. Compare nodes with is, and test for None with is None or is not None, since there is only one None object.

Taught in Linked lists
Immutable · also immutability

Cannot be changed after it is made. Strings, numbers and tuples are immutable. s[0] = "S" raises a TypeError, and no string method changes the string it is called on: s.upper() hands back a new string. To build a string piece by piece, collect the pieces in a list and call "".join(pieces) once.

Taught in Python, one step at a time
In place

Changing an existing list itself instead of building a new one. nums[1] = 9, nums.append(4) and nums.sort() all work in place, so every name for that list sees the change. append and sort return None: the changed list is the result.

Taught in Python, one step at a time
In-degree

The number of edges pointing into a node. In a dependency graph, it is how many tasks a task still waits for, and a task with in-degree 0 is ready to run. Kahn's algorithm lowers a task's in-degree by 1 each time a task it waits on is taken.

Taught in Graphs
Index · also position

The number of a box in a list, or of a character in a string, counting from 0. With nums = [12, 30, 7], nums[0] is 12 and the last index is len(nums) - 1, which is 2. A negative index counts from the end: nums[-1] is 7.

Taught in Python, one step at a time
Input size (n) · also n

The size of the input, usually the number of items in the list. Costs are stated in terms of n: one loop over the list makes n passes. With two inputs, give each its own letter, such as n and m.

Taught in Counting steps: Big O
Insertion sort

A sort that keeps a sorted part at the front of the list and grows it one item per pass: the next item swaps left while its left neighbor is bigger. O(n2) comparisons in the worst case (a list in reverse order), n − 1 on a list that is already sorted, and O(1) extra space.

Taught in Sorting and binary search
Integer overflow · also overflow

What happens when a result is too big for a fixed-size integer: it comes out wrong. A 32-bit integer holds at most 2,147,483,647. Python integers grow as needed and never overflow, so 1 + 2 + ... + 100,000 = 5,000,050,000 is exact. In a fixed-size language, use a 64-bit type or a method whose numbers stay small, such as XOR.

Taught in Greedy and a little math
Interval

A pair [start, end] with start <= end: a stretch of time or of numbers. Two intervals overlap when each starts at or before the other ends, a[0] <= b[1] and b[0] <= a[1]. Whether touching intervals such as [1, 3] and [3, 5] overlap changes from problem to problem, so ask.

Taught in Sorting and binary search
Interval DP · also interval dynamic programming

Dynamic programming whose state is a stretch of the input named by its two ends, best[left][right], filled from short stretches to long ones so the pieces inside each stretch are ready. Burst balloons splits each stretch on the balloon that bursts last. Typically O(n3) time and O(n2) space.

Taught in Dynamic programming
K-way merge · also merge k sorted lists, heap of fronts

Merging k sorted lists into one by keeping a heap of each list's current front, as (value, list number, position) entries. Pop the smallest, add it to the answer, and push the next value of the same list, if it has one. The heap never holds more than k entries, so N values cost O(N log k) time. It is the merge step of an external sort, where each sorted run on disk sends in one front at a time.

Taught in Heaps and tries
Kadane's algorithm · also extend or restart, maximum subarray

The one-pass walk for the largest sum of a run (a subarray). At each position it keeps current, the best sum of a run that ends exactly there: current = max(nums[i], current + nums[i]), which means extend the run behind you, or restart here when that run adds up to less than zero. A second number, best, keeps the largest current seen. O(n) time, O(1) extra space. Start both at nums[0], not 0, so that an all-negative list gets its largest item.

Taught in Greedy and a little math
Lambda · also anonymous function

A one-line function with no name: lambda order: order[1] takes order and returns order[1]. The name before the colon is the parameter; the expression after it is the result. Most often written as a sort key: sorted(orders, key=lambda order: order[1]).

Taught in Sorting and binary search
Leap of faith

Writing or checking a recursive function by trusting that the call on a smaller input returns the right answer, instead of tracing every frame. Three checks replace the trace: the base case is right, every call moves toward a base case, and the combine step is right if the smaller answer is. When all three hold, every call is right, from the base case up.

Taught in Recursion and trees
Level-order traversal · also level order, BFS on a tree

Visiting a tree one level at a time, top to bottom, each level left to right, with a queue: take the front node, record it, send its children to the back. At the start of each round the queue holds exactly one level, so for _ in range(len(queue)) takes that level and nothing more. O(n) time and O(w) space, where w is the number of nodes on the widest level. It answers level questions: the right side view is the last node of each round, and the minimum depth is the round of the first leaf taken.

Taught in Recursion and trees
Linked list · also singly linked list

A chain of nodes, each holding a value and a pointer to the next node; the last node points at None. You hold a linked list by its first node, the head, and an empty list is a head of None. There are no positions: reaching the k-th node takes k steps from the head. In exchange, adding a node at the front is one step, head = ListNode(v, head), however long the list is.

Taught in Linked lists
Linked list cycle

A loop in the links: some node's next points back to an earlier node, or to itself, so a walk that waits for None never ends. A cycle means reaching the same node object again, not meeting an equal value, so checks compare nodes with is.

Taught in Linked lists
List comprehension · also comprehension

A loop that builds a list, written as one expression. [x * x for x in nums if x % 2 == 0] keeps the square of every even x in nums. Read it from the for, then the if, then the expression on the left.

Taught in Python, one step at a time
ListNode · also list node

The node class every lab cell already has, the same one LeetCode uses: ListNode(val, next). val is the value the node holds and next is the node after it, or None after the last node. next is a pointer, also called a link: it leads to the next node itself, not a copy of its value. cur = cur.next moves the name cur along the list; cur.next = other changes the list.

Taught in Linked lists
Load factor

The number of keys in a hash map divided by its number of buckets: 6 keys in 8 buckets is 0.75. It is the average chain length. The table keeps it low by doubling its buckets when an add would push it past a limit.

Taught in Arrays and hash maps
Log scale

A chart axis where each gridline is a fixed multiple of the one below, such as 10 times, instead of a fixed amount more. It fits tiny and enormous counts on one chart: 4 steps and 21 trillion steps can sit on the same axis.

Taught in Counting steps: Big O
Logarithm · also log n, base-2 logarithm

log⁡2n\log_2 n is the power you raise 2 to in order to get n: log⁡216=4\log_2 16 = 4 because 2 × 2 × 2 × 2 = 16. It is also about how many times you can halve n before reaching 1, so a loop that halves what is left runs log⁡2n\log_2 n times, rounded down: 19 passes for a million items. In this course, log n means log base 2.

Taught in Counting steps: Big O
Longest common subsequence · also LCS

The longest string that is a subsequence of both of two strings: for "cat" and "act" it has length 2 ("ct" or "at"). The table cell best[i][j] holds the answer for the first i letters of one and the first j of the other. A match adds 1 to the cell above-left; otherwise the cell takes the larger of above and left. O(m × n) time.

Taught in Dynamic programming
Longest increasing subsequence · also LIS

The longest subsequence of a list in which each item is strictly bigger than the one before. Fix where it ends: ends_here[i] is 1 plus the largest ends_here[j] over earlier, smaller items, and the answer is the largest cell, in O(n2) time. A sorted tails list with binary search (patience sorting) finds the length in O(n log n).

Taught in Dynamic programming
Lowest 1 bit · also lowest set bit, x & (x - 1)

The rightmost 1 in a number's binary form. x & (x - 1) is x with that bit turned off: subtracting 1 turns the lowest 1 into a 0 and the 0s below it into 1s, and & keeps only the 1s both numbers share. 44 is 101100 and 43 is 101011, so 44 & 43 is 101000, which is 40. Repeating it until x is 0 counts the 1 bits, one pass per 1.

Taught in Greedy and a little math
Lowest common ancestor · also LCA

For two nodes p and q, the node farthest from the root that is an ancestor of both. An ancestor of a node is any node on the path from the root down to it, the node itself included. The paths from the root to p and to q share a top part, then split; the last shared node is the answer. In any binary tree, each call reports p, q, the answer or None, and a node whose two sides both report something is the answer: O(n). In a binary search tree, walk down while both values are on the same side: O(h).

Taught in Recursion and trees
LRU cache · also least recently used cache

A cache (a small, fast store of copies of things that are slow to fetch) with a fixed capacity that, when full, evicts the least recently used key: the one whose last use is furthest in the past. A use is a get that finds its key, or any put. A dict from key to node plus a doubly linked list of the nodes in order of use makes get and put O(1) on average: the dict finds the node, and the list moves it to the newest end or gives up its oldest node. LeetCode 146.

Taught in Linked lists
Mark and unmark · also in-place marking

Keeping a path's cells on the grid itself: overwrite a cell with a marker such as "#" when the path enters it (choose), and put the original letter back when the path leaves (unchoose). The marker matches no letter, so the letter test also rejects cells already on the path. Without the mark a path can reuse a cell; without the unmark, later paths miss answers.

Taught in Backtracking
Max-heap · also max heap

A heap with the opposite promise: no parent is smaller than its children, so the largest item is at index 0. With heapq, store each number negated: the largest number becomes the smallest entry and comes out first. Push -x, and flip the sign back when you read it, -heap[0] or -heapq.heappop(heap).

Taught in Heaps and tries
Memoization · also memo, memoize

Keeping a notebook of answers for a recursive function: store each answer in a dict, the memo, the first time a call works it out, and look it up after that. A call looks in the memo before making calls of its own, so each different question is worked out once. With a memo, fib(n) makes 2n − 1 calls for n ≥ 1 instead of an exponential number. Module 12 builds dynamic programming on it.

Taught in Recursion and trees
Memory address · also address

The number that names one byte of the computer's memory. A list keeps its items in one block of slots, side by side, so nums[i] sits at start + i × slot size. Working that out is one multiplication and one addition, which is why reading any index is O(1).

Taught in Arrays and hash maps
Merge from the back

Merging two sorted lists into the first one, when its free room is at the end: start with write at the last slot and fill each slot with the larger of the two values still waiting, moving left. A write never lands on a value that has not been placed yet, because write always equals i + j + 1. O(m + n) time, O(1) extra space.

Taught in Two pointers and sliding windows
Merge sort

A sort that splits a list in half again and again until every piece holds one item, then merges the pieces back in pairs. About log n levels of n steps each: O(n log n) time, O(n) extra space.

Taught in Sorting and binary search
Merging sorted lists · also merge

Combining two sorted lists into one sorted list in a single pass. Keep one index per list, compare the two front items, take the smaller and move that index; when one list runs out, add the rest of the other. O(n) time for n items in total.

Taught in Sorting and binary search
Min stack

A stack that can also report its smallest value in O(1). Each value is stored as a pair (value, smallest), where smallest is the minimum of that value and every value beneath it, so the top pair always holds the minimum of the whole stack and a pop never loses it.

Taught in Stacks and queues
Miss types · also error journal, knowledge gap, careless miss, concept miss, procedure miss

The four reasons a problem beats you, logged in the error journal: knowledge gap (you never learned the pattern), procedure (you knew the approach and fumbled the code), careless (a slip such as an off-by-one or a misread constraint) and concept (a wrong model of the cost or the data structure). The most common type decides what to drill next.

Taught in The interview and this lab
Mixed practice · also interleaved practice, interleaving, mixed set

Practice that shuffles problems from different patterns, so each one starts with the question "which pattern is this?" Its opposite, blocked practice, works one pattern at a time. Meet a new pattern blocked (3 to 5 problems in a row), then switch to mixed sets.

Taught in The interview and this lab
Mock round · also mock, mock interview

A practice interview under real conditions: an unseen problem, a clock, no Run button, and narration out loud the whole time. Average scores cross the passing threshold after about five mocks (platform data), so judge readiness on the trend across your last five, never on one.

Taught in The interview and this lab
Modulo · also mod, remainder, %

a % b is the remainder left after a // b: 17 % 5 is 2, because 5 fits into 17 three times with 2 left over. x % 2 == 0 asks whether x is even, and n % 10 is the last digit of a positive n.

Taught in Python, one step at a time
Monotonic deque

A deque of indexes whose values only fall from front to back. A new item knocks out smaller or equal values from the back, and an index that slides out of the window leaves from the front, so the front is always the window's largest. It gives the largest number in every window of k items in O(n).

Taught in Stacks and queues
Monotonic stack

A stack whose values never rise (or, in other problems, never fall) from bottom to top. Before a new item is pushed, it pops every item on top that would break the order. For next greater element, the item that pops an index is that index's answer. Each index is pushed once and popped at most once, so a whole walk is O(n).

Taught in Stacks and queues
Multi-part build · also escalating build

A round where one program grows in parts: once part 1 works, the interviewer adds a requirement, then another, and each part keeps every rule of the parts before it. The skill is a part 1 that survives part 2: only the class's methods touch the notebook, each mechanism lives in its own small function, and each part is tested before the next.

Taught in Interview mode
Multi-source BFS · also multi-source breadth-first search

Breadth-first search that starts with every source in the queue at distance 0, such as every rotten orange at once. Each round then reaches everything one step further from the nearest source, so one round can stand for one minute. It costs the same as a search from a single start, because each node still joins the queue once.

Taught in Graphs
N-Queens · also eight queens

The puzzle of placing n queens on an n by n board so that no two share a row, a column or a diagonal. Each row holds one queen, so the search chooses a column per row and prunes attacked squares with three sets: columns, row - col and row + col. For n = 8 there are 92 placements, found in 2,057 calls.

Taught in Backtracking
Next greater element

For each item in a list, the first item to its right that is strictly bigger, or -1 if there is none. The first bigger item, not the biggest: in [3, 1, 2, 5] the 1's answer is 2. Scanning right from every item is O(n2); a monotonic stack finds every answer in one O(n) walk.

Taught in Stacks and queues
No-execution checklist · also self-test checklist

The order for testing code you cannot run: reread it once, trace a typical case aloud, trace an empty and a one-item input, trace duplicates and boundaries, check every loop bound, check None and not-found paths, confirm that base cases and early returns fire, then state time and space and say done. Announce a bug before you fix it, and trace the edge cases again after the fix.

Taught in Interview mode
None

Python's value for "no value", the job NULL does in a table. A function that ends without a return hands back None, one of the most common reasons a first solution fails its tests.

Taught in Python, one step at a time
None path · also not-found path

A way through the code on which a name can hold None: an empty linked list or tree, the next of the last node, a child of a leaf. Any .next, .left, .right or .val read on that path crashes, so it needs a guard. Its quieter cousin is the not-found path: a search that returns only inside its loop gives back None when the loop ends without a match.

Taught in Interview mode
nonlocal

A Python statement in a function defined inside another, such as nonlocal best, saying that the name belongs to the outer function, so assigning to it changes that outer variable. Without it, any assignment to best inside the inner function makes best a new name of the inner function, and reading it before that assignment raises UnboundLocalError. Reading an outer name, or changing the list or dict it points at (out.append(x), memo[k] = v), needs no nonlocal.

Taught in Recursion and trees
Notebook

What an algorithm writes down as it walks, so it never has to look back. For the largest number it is one name, best. For the one-pass duplicate check it is a set, seen, of the numbers already passed. The second part of the frame.

Taught in The interview and this lab
Off-by-one error · also off-by-one, off by one

A loop or slice that goes one step too far or stops one step short, such as range(len(nums) - 1) where every position was meant. range(a, b) gives a up to b - 1, so check the first and last value of every loop variable.

Taught in Python, one step at a time
Operand

A value an operator works on. In 6 - 5, 6 is the left operand and 5 the right one. When a postfix evaluator pops two operands off its stack, the first pop is the right operand, because it arrived later.

Taught in Stacks and queues
OrderedDict · also collections.OrderedDict

A dict from collections that remembers the order of its keys and reorders them in O(1): move_to_end(key) sends a key to the back, and popitem(last=False) removes and returns the front pair. Assigning a new value to a key that is already there does not move it. Inside, it is a hash map plus a doubly linked list, which makes it a short LRU cache; in an interview, name it and offer to build the linked list by hand.

Taught in Linked lists
Palindrome

A word or string that reads the same forwards and backwards, such as "radar" or "noon". Two pointers check one by comparing mirror pairs (the first character with the last, the second with the second to last) and stopping at the first pair that differs: O(n) time, O(1) extra space.

Taught in Two pointers and sliding windows
Permutation · also ordering, arrangement

One way to line up all the items in a row, using each exactly once. Order matters: [a, b] and [b, a] are two permutations. n different items have n! of them, so 3 items have 6. Backtracking builds them one spot at a time, trying every item not yet placed.

Taught in Backtracking
Pointer · also link

A reference that leads to another object instead of holding a copy of it: a node's next points at the next node itself. Following one is one step. The word has two meanings in this course. In two pointers and sliding windows (module 4) it means an index into a list; in linked lists and trees it means a reference to a node.

Taught in Linked lists
Postfix notation · also reverse Polish notation, RPN

A way to write arithmetic where each operator comes after the two values it combines, not between them: 2 3 + means 2 + 3, and 2 3 + 4 * means (2 + 3) * 4. The order of the tokens says what to compute first, so no parentheses are needed. It is evaluated with a stack of values waiting for an operator.

Taught in Stacks and queues
Power of two

One of 1, 2, 4, 8, 16 and so on: a number with exactly one 1 bit. So x > 0 and x & (x - 1) == 0 tests for one. The x > 0 part matters, because 0 & -1 is also 0.

Taught in Greedy and a little math
Prefix maxima · also prefix max, running maximum list

A list whose position i holds the largest item from the start up to i: the running maximum, written down at every position. For [3, 1, 2, 4, 0, 2] it is [3, 3, 3, 4, 4, 4]. One pass, O(n) time. It is prefix sums with max in place of +, and it finds every bar's left wall in trapping rain water.

Taught in Interview mode
Prefix product · also suffix product, suffix

The product of the items before position i, written before[i]. A product of nothing is 1, so before[0] is 1. The suffix product after[i] is the product of the items after i; a suffix is a run that ends at the last item. One walk from the left fills before, one walk from the right fills after, and before[i] * after[i] is the product of every item except nums[i], with no division.

Taught in Arrays and hash maps
Prefix sum · also prefix sums, cumulative sum

A list where prefix[i] is the sum of the first i items, with prefix[0] = 0, so it is one longer than the list. Built in one walk, it turns the sum of positions left to right into one subtraction: prefix[right + 1] - prefix[left].

Taught in Arrays and hash maps
Preorder, inorder and postorder · also preorder, inorder, postorder, depth-first traversal

The three depth-first orders for visiting a tree. The recursive walk is the same for all three; only the moment a node is written changes. Preorder writes the node, then its left subtree, then its right subtree. Inorder writes the left subtree, the node, then the right subtree, which lists a binary search tree's values in sorted order. Postorder writes both subtrees, then the node, so every node comes after its children: the order in which answers travel up a tree.

Taught in Recursion and trees
Promise · also invariant, loop invariant

A sentence about the notebook that is true after every step of the walk. For a running maximum: after each pass, best is the largest of the numbers visited so far. When the walk ends, the promise becomes the answer, which is why the code is correct. Interviewers call it the invariant. The third part of the frame.

Taught in The interview and this lab
Pruning · also prune test, cutting a branch

Skipping a branch of the choice tree the moment its path cannot lead to an answer. The prune test runs before a choice is made, so nothing below a failed choice is ever built. A good test is safe (it never cuts a path that can still be finished), early (it runs before the choice) and cheap (O(1), thanks to a notebook of counts, sums or sets).

Taught in Backtracking
Push, pop and peek · also top of the stack

The three stack moves. Push puts an item on top (stack.append(x)). Pop removes the top item and hands it back (stack.pop()). Peek reads the top without removing it (stack[-1]). Pop and peek on an empty list raise an IndexError, so check if stack: first when the stack could be empty.

Taught in Stacks and queues
Queue · also FIFO, first in, first out

A line where items join at the back and leave from the front, so the item that has waited longest leaves first. It is the notebook for work done in arrival order, such as files to load or the people still to visit in a breadth-first walk. In Python, use a deque: append to join, popleft() to leave, both O(1). list.pop(0) gives the same order but costs O(n).

Taught in Stacks and queues
Re-solve ladder · also spaced practice, spacing, re-solve schedule

This lab's schedule for solving a problem again from a blank editor. Each clean solve moves it up one rung, so the next re-solve comes 1, 3, 7, 14, then 30 days after the latest solve, and a sixth clean solve in a row, done in mock mode, retires it. A re-solve counts as clean only within 15 minutes (20 for a hard problem). A solve that needed help, or a slow re-solve, sends it back to 1 day. It puts spaced practice (practice spread over days instead of crammed into one sitting) into action.

Taught in The interview and this lab
Read and write pointers · also read pointer, write pointer

Two indexes that walk one list in the same direction to edit it in place. read visits every item once; write is the slot where the next kept item goes. The promise: nums[:write] is the finished answer for the items read so far. Because write never passes read, no item still waiting to be read is overwritten. Filter in place, drop repeats from a sorted list, and move zeroes to the end all use it.

Taught in Two pointers and sliding windows
Recurrence · also recurrence relation

A rule that gives the answer for an input from the answers for smaller inputs, plus base cases that need no rule. Find one by asking how the last move was made: every climb of a staircase ends with a stride of 1 or 2, so ways(n) = ways(n - 1) + ways(n - 2), with ways(0) = ways(1) = 1.

Taught in Dynamic programming
Recursion · also recursive function

Solving a problem with a function that calls itself on a smaller version of the same problem. Every recursive function has a base case, answered outright, and a recursive case that calls the function on a smaller input and uses its answer. factorial(n) returns 1 when n <= 1 and n * factorial(n - 1) otherwise. Trees have the same shape: a node with smaller trees under it.

Taught in Recursion and trees
Recursion limit · also RecursionError, maximum recursion depth

The most nested calls Python allows before it stops with a RecursionError. Plain Python stops at about 1,000 by default; this lab allows 5,000, and sys.setrecursionlimit raises the limit. A recursion that goes one level per item or per tree level fails on deep inputs, such as a chain of 100,000 nodes. The fix is a loop with a stack or a queue of your own, or, where the problem allows, a recursion that halves its input.

Taught in Recursion and trees
Reference

The address of a value, which lives elsewhere in memory. A list slot holds a reference, not the value itself, so every slot is the same size (8 bytes on a 64-bit machine) whether it points at 7 or at a long string. Repeating a reference shares one value: [[0] * 3] * 2 makes two slots that point at the same row.

Taught in Arrays and hash maps
Rehashing · also resizing a hash table

Placing every key again after a hash map changes its number of buckets, usually by doubling. Each key's bucket is worked out afresh with the new count, because key % 8 is not always key % 4. It costs O(n) for that one add, but it is rare enough that adds stay amortized O(1).

Taught in Arrays and hash maps
Repeated work

What a brute force computes again and again, such as rescanning a prefix for its maximum or rebuilding a window from scratch. Finding it is the middle of the three moves for an unseen hard: say the brute force and its cost, find the repeated work, name the pattern whose notebook stops it (a running value, a hash map, a window, a heap).

Taught in Interview mode
Retrieval practice · also retrieval

Pulling an answer out of your own memory instead of reading it again: closing a solution and writing it from a blank editor. In one study, people who practiced recall remembered about 61% of the material a week later, against about 40% for people who reread it.

Taught in The interview and this lab
Reversing a linked list · also in-place reversal

Pointing every next the other way without making new nodes. Walk with three names: prev, the head of the part already reversed (at first None); cur, the node we are on; and nxt, the rest of the list. Each pass saves, flips, then moves: nxt = cur.next, cur.next = prev, prev = cur, cur = nxt. When cur is None, prev is the new head. O(n) time, O(1) extra space.

Taught in Linked lists
Rotated sorted list · also rotated sorted array

A sorted list cut in two with the pieces swapped, such as [4, 6, 8, 10, 12, 1, 2]: it climbs, drops once, and climbs again. The smallest item sits right after the drop. Split any range at its middle and one of the two halves is in plain sorted order.

Taught in Sorting and binary search
Running total, count and maximum · also running total, running count, running maximum, running max

A loop's notebook of one value, updated once per item, with a promise that holds after every pass: total is the sum of the items visited so far, count is how many of them passed a test, best is the largest so far. When the walk ends, the promise is the answer. Start a running maximum at nums[0] or float("-inf"), not at 0, unless every value is known to be 0 or more: best = 0 gives 0 for [-6, -3, -8].

Taught in Python, one step at a time
Saving a copy of the path · also path[:], snapshot of the path

At a leaf, save path[:] (or list(path)), a new list holding what path holds right now, not path itself. Backtracking keeps changing one shared path, and it ends empty, so result.append(path) would save that one list again and again (aliasing). A string built with "".join(path) is already a new value.

Taught in Backtracking
Seating values in place · also list as its own hash map, cyclic sort

Using a list as its own hash map: when the values that matter are 1 to n, seat v - 1 holds the value v. Swap each value into its seat, staying at an index until its value is out of range or its seat already holds a copy; every swap seats one value for good, so the pass makes at most n swaps. Then the first seat that does not hold its own value names a missing value, in O(n) time and O(1) extra space.

Taught in Interview mode
Seen-before · also seen set

The pattern that walks a list with a set (or dict) of the items already passed, and for each new item checks whether it is in there before adding it. It finds repeats in one O(n) walk. Asked about target - x instead of x, with a dict of positions, it solves two sum.

Taught in Arrays and hash maps
Sentinel node · also sentinel

A spare node at an end of a linked list that holds no real data and never leaves the list. The LRU cache keeps one at each end, head before the oldest node and tail after the newest; an empty list is the two sentinels pointing at each other. Every real node then has a node on both sides, never None, so unlinking and appending need no special cases. A dummy head is a sentinel at the front.

Taught in Linked lists
Short-circuiting · also short-circuit evaluation

and stops at the first false side and or stops at the first true side, without looking at the rest. That lets a check on the left guard a read on the right: i < len(nums) and nums[i] > 0 never reads nums[i] when i is past the end.

Taught in Python, one step at a time
Sift down · also bubble down

How a pop keeps the heap's promise. Take the smallest from index 0, move the last item into the hole, then swap it with its smaller child while it is bigger. The smaller child moves up because it is no bigger than its sibling, so both of its new links keep the promise. At most one swap per level, so O(log n).

Taught in Heaps and tries
Sift up · also bubble up

How a push keeps the heap's promise. Append the new item at the end of the list, the only spot that keeps the tree complete (no gaps), then swap it with its parent while it is smaller. It stops at index 0 or at a parent no bigger than it. At most one swap per level, so O(log n).

Taught in Heaps and tries
Signal · also problem signal

A phrase in a problem statement that says what the notebook must remember, and so points to a pattern. "For each item, the next bigger one" means items still waiting for an answer, which is a monotonic stack; "the fewest steps" means a queue in order of distance, which is breadth-first search. Read the input first, then what the question asks, then the size limit.

Taught in Interview mode
Slice

A new list or string cut from neighboring positions. nums[start:stop] includes start, stops before stop, and holds stop - start items: with nums = [12, 30, 7, 25], nums[1:3] is [30, 7]. nums[:] slices everything, which makes a copy.

Taught in Python, one step at a time
Sliding window · also window, rolling window

A block of consecutive items in a list or string, from index left to index right, both included, plus a notebook about the items inside it (a sum, a count, a set). The window moves by adding the item that enters on one side and removing the item that leaves on the other, so the notebook is updated, never rebuilt from scratch.

Taught in Two pointers and sliding windows
Space complexity · also extra space

How much extra memory an algorithm keeps as n grows, beyond the input it was handed: the size of its notebook. A few names is O(1); a list or set that gains an item per pass is O(n). Recursion counts too: every unfinished call keeps a box of names on the call stack.

Taught in Counting steps: Big O
Stable sort · also stability

A sort that keeps items with equal keys in the order they had before the sort. Python's sorted and list.sort are stable, also with reverse=True: sorting [("cy", 30), ("ana", 30)] by amount keeps "cy" first.

Taught in Sorting and binary search
Stack · also LIFO, last in, first out

A pile where items are added and removed only at one end, the top, so the last item in is the first item out. In Python, a plain list used only at its end: append adds to the top and pop() removes from it, both O(1) (append amortized). Reach for one when the newest unfinished item is the one you need next, as with nested brackets or an Undo button.

Taught in Stacks and queues
Start index · also start parameter

An argument, often start, that lets a backtracking call try only the choices at index start or later, so each combination is built once instead of once per order. Passing i to the next call lets the same item come again; passing i + 1 uses each item at most once. With sorted choices, a choice that is too big can break the loop, because every later one is bigger.

Taught in Backtracking
State · also DP state

The few facts that pin down one subproblem: the key of the memo and the address of a table cell. Say it in one sentence, such as "dp[i] is the most cash from the first i houses". The state is what the rest of the problem needs to know about the choices already made, and nothing more: for painting houses, the house i and the color it got, not the money spent so far.

Taught in Dynamic programming
Step

One simple operation, such as adding two numbers, comparing two values or reading one item of a list. Each step takes about the same short time whatever the input size, so the cost of code is how many steps it makes. In practice you count how many times a loop body runs.

Taught in Counting steps: Big O
Struggle cap

How long to fight a problem before you look: 20 to 35 minutes of genuine attempt (a brute force written, an example traced by hand), then read the approach and re-solve the problem from scratch on a later day. Staring at the prompt does not count as an attempt.

Taught in The interview and this lab
Stuck recovery script · also recovery script

Five moves for when no better idea comes: say where you are within about a minute of silence, work a small example by hand, say what you have ruled out and why, restate any hint in your own words and use it, and announce the pivot when you change approach.

Taught in Interview mode
Subarray · also contiguous subarray

One or more items that sit next to each other in a list, like nums[1:4]. A list of n items has n(n + 1)/2 of them, which is why trying every subarray costs O(n2) or more.

Taught in Arrays and hash maps
Subproblem · also overlapping subproblems

A smaller version of the problem being solved, such as fib(3) inside fib(6). When the same subproblem shows up in more than one place in a call tree, the subproblems overlap, and storing each answer removes the repeats: fib(6) makes 25 calls but needs only 7 different answers.

Taught in Dynamic programming
Subsequence

What is left of a string or list after deleting any items you like (possibly none) without changing the order of the rest. "ct" is a subsequence of "cat", and "tc" is not. Unlike a substring or subarray, the kept items do not have to sit next to each other.

Taught in Dynamic programming
Subset sum

Can some of the numbers, each used at most once, add up to exactly a target? It is a 0/1 knapsack whose cells hold True or False, or a set of the sums reachable so far. Splitting a list into two groups with equal sums is subset sum with half the total as the target.

Taught in Dynamic programming
Substring

A block of consecutive characters of a string: "cbd" is a substring of "abcbde", but "acd" is not, because its characters do not sit next to each other. In Python, s[left:right + 1] is the substring from left to right, both included.

Taught in Two pointers and sliding windows
Sum of 1 to n · also n(n + 1) / 2

1 + 2 + ... + n is n(n + 1) / 2. Write the numbers forward and again backward underneath: each of the n columns adds up to n + 1, and the two rows hold twice the sum. For n = 5 it is 15. In code, n * (n + 1) // 2 stays a whole number. The missing number problem compares this expected total with the actual one.

Taught in Greedy and a little math
Sweep line · also line sweep

A walk through time in the sorted order of events: each start takes a resource such as a room, each end gives one back, and a running count tracks how many are in use. When an end and a start fall at the same time and a room is free the moment its meeting ends, the end goes first.

Taught in Sorting and binary search
Switches once · also monotonic

A yes/no question about a number x switches once when it says no up to some x and yes for every bigger x (or yes, then no). Only such a question can steer a binary search. "Does speed k finish within 6 hours?" switches once as k grows; "does it take exactly 6 hours?" can switch back.

Taught in Sorting and binary search
Think-aloud script · also live-round protocol, clarify, plan, implement, test, summarize

The five phases of a 45-minute coding round, with their minutes from the research digest: clarify (2 to 3), plan (3 to 4), implement (12 to 15), test (5 to 7) and summarize (2). Each phase feeds one of the four scores most, and talking through every phase feeds communication.

Taught in Interview mode
Tiebreaker

The middle item of a heap entry such as (key, tiebreaker, item). Python compares tuples item by item, so the tiebreaker decides only when the keys are equal. Use something that never ties, such as an arrival counter or a list number, so Python never compares the items themselves: two dicts or two ListNodes cannot be ordered, and comparing them raises TypeError.

Taught in Heaps and tries
Timsort

The sort behind Python's sorted and list.sort, a mix of merge sort and insertion sort. It finds runs (stretches already in order), lengthens short ones with insertion sort, and merges runs. Stable, O(n log n) in the worst case, and about n comparisons on a list that is already sorted.

Taught in Sorting and binary search
Tombstone · also delete marker

A marker value, such as None, written in place of a real value to record a delete. In a history of timestamped writes, a delete becomes one more write, so questions about earlier seconds still find the old values and the search does not change.

Taught in Interview mode
Top k with a heap · also k largest, kth largest, top-N

Finding the k largest items by keeping a min-heap of at most k of them: push each item, and pop once when the heap holds k + 1. The pop removes the smallest kept item, which cannot be among the k largest, and heap[0] is the kth largest so far. O(n log k) time and O(k) space, so it also works on a stream too big to store. For the k smallest, the largest kept item leaves, so keep a max-heap by pushing -x. The rule for both: the heap's top is the item that leaves next.

Taught in Heaps and tries
Top-down · also top-down DP, memoized recursion

Dynamic programming that starts from the big question, recurses toward the base cases, and stores each answer in a memo on the way back. It is the plain recursion plus a few lines. It goes one call deeper per level, so a large input can pass plain Python's default limit of about 1,000 nested calls.

Taught in Dynamic programming
Topological order · also topological sort

An order of the nodes of a directed graph in which every edge points from an earlier node to a later one: every task comes after the tasks it waits for. A graph often has several, and it has none when it contains a cycle. Kahn's algorithm builds one: queue every task whose in-degree is 0, take one, and lower the in-degree of each task that waits on it. If fewer than all the tasks come out, there is a cycle.

Taught in Graphs
Trace · also tracing, hand trace, dry run

Following code one line at a time with real values, keeping track of what every name holds. It is how you test code when nothing runs. In this lab a trace is also the step-through figure: the code on one side, every name and its value on the other.

Taught in The interview and this lab
Traceback · also stack trace

What Python prints when an error stops a program: the chain of calls that led to the error, with the error itself on the last line. Read it from the bottom up. The line it names is where Python noticed the problem, which is not always where the bug is.

Taught in Python, one step at a time
Transaction

A group of changes kept or undone as a whole. begin opens one, commit keeps every change made since, and rollback undoes them all, so the store returns to how it stood at begin. In SQL these are BEGIN, COMMIT and ROLLBACK.

Taught in Interview mode
Transition · also transition rule

The rule that computes one cell of a dynamic programming table from cells already filled: the recurrence written in terms of cells. For house robber it is dp[i] = max(dp[i - 1], dp[i - 2] + money[i - 1]): skip the newest house, or rob it on top of the best two houses back.

Taught in Dynamic programming
TreeNode · also tree node

The tree node class every lab cell already has, the same one LeetCode uses: TreeNode(val, left, right), where left and right are its children, or None when missing. build_tree makes a tree from a list in level order: the root, then each level from left to right, with None for a missing child. Every real node takes the next two values as its children, and a None takes none. tree_values turns a tree back into that list.

Taught in Recursion and trees
Trie · also prefix tree

A tree of letters that stores words. The root stands for the start, before any letter, and every other node holds one letter. The path from the root to a node spells a prefix, so words that start alike share their first nodes: "cat" and "car" share c and a. Each node has children keyed by the next letter and an end-of-word mark. Insert, search and starts-with each cost O(L) for L letters, however many words are stored.

Taught in Heaps and tries
TrieNode · also trie node

The class version of a trie node: self.children = {} maps each next letter to its child TrieNode, and self.is_end = False turns True where a stored word ends. Create children inside __init__, so each node gets its own dict. A dict written in the class body, or as a default argument, is one dict shared by every node.

Taught in Heaps and tries
Two pointers · also pointers from both ends, left and right pointers

A pattern that keeps two indexes into one list or string and moves them by rules. An index used this way is called a pointer. In the version from both ends, left starts at position 0 and right at the last position, and they move toward each other while left < right. Each move skips an item that has been proved unable to be part of a better answer, so one walk is O(n), where checking every pair is O(n2).

Taught in Two pointers and sliding windows
Two-heap median · also running median, median of a stream

The median of numbers that arrive one at a time, kept by two heaps facing each other: low, a max-heap (stored negated) of the smaller half, and high, a min-heap of the larger half. Every number in low is at most every number in high, and low holds as many numbers as high or one more. The median is -low[0] for an odd count, or the average of the two tops for an even count. Adding a number is O(log n); reading the median is O(1).

Taught in Heaps and tries
Two-stack queue · also queue from two stacks

A queue built from two stacks. New items are pushed onto in_stack. When the front is needed and out_stack is empty, every item moves from in_stack to out_stack, which reverses them so the oldest is on top. Each item moves at most once, so pop is O(1) amortized even though one call can move every item.

Taught in Stacks and queues
Undo record

For one open transaction, a dict from each key it changed to the value that key held before the transaction first changed it (None if it held nothing). Rollback puts those values back, in time proportional to the keys changed, not the size of the store. Nested transactions keep a stack of records, and an inner commit merges its record into the outer one, keeping the outer entry when both have the key.

Taught in Interview mode
Union by size and path compression

The two tricks that keep union-find fast. Union by size hangs the root of the smaller group under the root of the bigger one, so no item sits more than log₂ n steps below its root. Path compression points every item a find walks past straight at the root. Together they make each operation nearly O(1), amortized; without them, a bad order of unions builds a chain and a single find costs O(n).

Taught in Graphs
Union-find · also disjoint set union, DSU

A notebook for groups that only ever merge. Each item points at a parent, and following parents ends at a root, the item that names the group. find(x) walks up to the root, and union(a, b) points one root at the other, which moves a whole group with one write. Two items are in the same group exactly when their roots match, and an edge whose ends already share a root closes a cycle.

Taught in Graphs
Unpacking · also tuple unpacking

Taking a tuple (a fixed group of values written with commas, such as (3, 8)) apart into several names in one line: low, high = (3, 8). It gives the swap a, b = b, a, two return values with return low, high, and loops such as for i, x in enumerate(nums).

Taught in Python, one step at a time
Used list · also used array, used flags

A list of booleans, one per position, where used[i] is True while items[i] is in the path. An orderings search checks it in O(1) to skip items already placed, sets it on choose and clears it on unchoose. It tracks positions, not values, so two equal items still count as two.

Taught in Backtracking
Variable · also name

A name tied to a value, like a tag. x = 5 works out the right side first, then ties the name x to 5. A later x = x + 1 moves the tag to a new value (this is called rebinding); the old value itself never changes.

Taught in Python, one step at a time
Variable window · also variable-size window, window that grows and shrinks

A sliding window whose size changes. right moves one step every pass; while the window breaks the rule, left moves forward. For a longest answer, record after the shrink loop; for a shortest answer, record inside it, before each shrink. Each pointer moves at most n times, so the walk is O(n) even with a while loop inside the for loop. It works when growing the window can only break the rule and shrinking can only repair it, which is why sums with negative numbers do not fit.

Taught in Two pointers and sliding windows
Walk

The order in which an algorithm visits the data. Finding the largest number walks left to right, each number once. Checking every pair walks every pair of positions i < j, each pair once. The first part of the frame.

Taught in The interview and this lab
Worst case

The input of a given size n that needs the most steps. For a search that stops at the first match, the worst case has the target last or missing: n passes. Interviews mean the worst case unless they say otherwise, because it holds for every input.

Taught in Counting steps: Big O
XOR · also ^, exclusive or

Exclusive or, written ^ in Python: a 1 where the two bits differ, a 0 where they match. x ^ x is 0, x ^ 0 is x, and the order does not matter, so XORing a whole list cancels every pair and leaves the XOR of the values seen an odd number of times. In Python ^ is not a power: 2 ^ 3 is 1, while 2 ** 3 is 8.

Taught in Greedy and a little math