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
- Taught in Dynamic programming
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 firstiitems within weightw: skip itemi, or take it on top of the row above. One row walked downward is enough. O(n × capacity) time. - Adjacency list
- Taught in Graphs
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 withdefaultdict(list): appendbto the list ofa, and for a two-way edge alsoato the list ofb. When the problem givesn, 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. - Aliasing · also alias
- Taught in Python, one step at a time
Two names for one object. After
b = a, whereanames a list,b.append(4)shows up throughatoo, because there is only one list. For a separate copy, writea[:]orlist(a). - Amortized cost · also amortized O(1)
- Taught in Counting steps: Big O
The average cost per operation over a long run of operations.
appendis 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. - Anagram
- Taught in Arrays and hash maps
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.
- Backtracking · also backtracking search
- Taught in Backtracking
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.
- Balanced binary tree · also height-balanced tree, balanced tree
- Taught in Recursion and trees
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).
- Base case
- Taught in Recursion and trees
The input a recursive function answers outright, with no further calls:
n <= 1for 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 skipsn == 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. - Best case
- Taught in Counting steps: Big O
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.
- Big O · also Big O notation
- Taught in Counting steps: Big O
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.
- Binary · also base 2, binary representation
- Taught in Greedy and a little math
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', and0b1101typed in code is the number 13. - Binary search
- Taught in Sorting and binary search
Searching a sorted range by looking at its middle and keeping only the half that can still hold the answer, so each look removes at least half of what is left: O(log n) time. The find template is
lo, hi = 0, len(nums) - 1, loopwhile lo <= hi, thenlo = mid + 1orhi = mid - 1, andreturn -1whenlopasseshi. - Binary search on the answer · also search on the answer
- Taught in Sorting and binary search
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.
lostarts at the smallest value that could work andhiat a value that surely works. The cost is one check times about log₂ of the range size. - Binary search tree · also BST
- Taught in Recursion and trees
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. - Binary tree
- Taught in Recursion and trees
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. - bisect · also bisect_left, bisect_right
- Taught in Sorting and binary search
Python's module for the first-true search on a sorted list.
bisect.bisect_left(nums, x)is the first index withnums[i] >= x, andbisect.bisect_right(nums, x)is the first index withnums[i] > x. Both return the length when no index qualifies, both cost O(log n), and their difference counts the copies ofx. - Bit · also binary digit
- Taught in Greedy and a little math
One binary digit: 0 or 1.
x & 1is the last bit ofx, the same asx % 2, andx >> 1drops it, the same asx // 2. A number n has about log₂ n bits: 13 has 4. - Bit shift · also <<, >>, left shift, right shift
- Taught in Greedy and a little math
Moving every bit of a number sideways.
x << 1moves each bit one place left and puts a 0 on the right, which doublesx.x >> 1moves each bit one place right and drops the last one, the same asx // 2. - Bitwise operators · also &, |, AND, OR, bitwise AND, bitwise OR
- Taught in Greedy and a little math
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 & 10is 8,12 | 10is 14 and12 ^ 10is 6. - Bottom-up · also tabulation, bottom-up DP
- Taught in Dynamic programming
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.
- Breadth-first search · also BFS
- Taught in Graphs
A graph search that visits nodes in rings: the start, then every node one edge away, then every node two edges away. A queue keeps that order, and each node is marked as it joins the queue. The first time the search reaches a node, it has found a path with the fewest edges, so it answers "fewest steps" questions when every step counts the same. O(V + E) time.
- Brute force
- Taught in The interview and this lab
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.
- Bucket
- Taught in Arrays and hash maps
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. - Bucket sort by frequency
- Taught in Arrays and hash maps
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. - Call stack
- Taught in Recursion and trees
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.
- Capacity · also spare room
- Taught in Arrays and hash maps
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). - Chaining · also separate chaining
- Taught in Arrays and hash maps
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.
- Choice tree · also state-space tree
- Taught in Backtracking
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.
- Choose, explore, unchoose · also backtracking template, choose, recurse, undo
- Taught in Backtracking
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, oftenpath.pop()). The undo keeps the promise that every call leaves the shared notebook as it found it, so the next option starts clean. - Clarifying question
- Taught in Interview mode
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.
- Class · also method, constructor, __init__, self
- Taught in Arrays and hash maps
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 inSlowSums(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 onself, such asself.nums, stays with that one object from one call to the next. - Collision · also hash collision
- Taught in Arrays and hash maps
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.
- Combination
- Taught in Backtracking
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. - Complete tree · also complete binary tree
- Taught in Heaps and tries
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.
- Complexity class
- Taught in Counting steps: Big O
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). - Conditional expression · also one-line if/else, ternary
- Taught in Python, one step at a time
An
if/elsethat 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 asreturn a if a > b else b. For three or more outcomes, write anif/elif/elsechain. - Connected component · also component
- Taught in Graphs
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.
- Constraints · also size limit
- Taught in Counting steps: Big O
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).
- Cost
- Taught in The interview and this lab
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.
- Costume · also deformed problem
- Taught in Interview mode
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.
- Counterexample
- Taught in Greedy and a little math
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.
- Cycle · also loop
- Taught in Graphs
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.
- Depth-first search · also DFS
- Taught in Graphs
A graph search that steps to an unvisited neighbor whenever it can and backs up only at a dead end. Write it with recursion, where a call returning is the backing up, or with a list used as a stack, where the newest node comes off first and there is no depth limit. Mark each node the moment you reach it. It costs O(V + E) time for V nodes and E edges, which is O(rows × cols) on a grid.
- Deque · also double-ended queue, collections.deque
- Taught in Stacks and queues
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). - Diagonal keys · also row - col, row + col, anti-diagonal
- Taught in Backtracking
One number that names a whole diagonal of a grid. Along a down-right diagonal
row - colstays the same; along an up-right diagonalrow + colstays the same. Sets of these numbers check both diagonals of a square in O(1), as in N-Queens. - Diameter of a binary tree · also diameter
- Taught in Recursion and trees
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. - Dict · also dictionary, lookup table
- Taught in Python, one step at a time
A lookup table from keys to values.
d = {}makes an empty one,d[k] = vstores a value,d[k]reads it (a missing key raisesKeyError),k in dasks whether a key is there, andd.get(k, 0)reads with 0 for a missing key. Counting iscounts[w] = counts.get(w, 0) + 1. A dict is Python's hash map: a lookup takes about one step on average. - Dijkstra's algorithm
- Taught in Graphs
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.
- Directed acyclic graph · also DAG
- Taught in Graphs
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.
- Directed and undirected graphs · also one-way edges, two-way edges
- Taught in Graphs
In a directed graph each edge goes one way and is drawn as an arrow: an edge from
rawtocleanlets you step fromrawtocleanbut 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. - Doubly linked list
- Taught in Linked lists
A linked list whose nodes have two pointers:
nextto the node after andprevto 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.nextandnode.next.prev = node.prev), and putting it next to a node you hold is four. Withnextalone, finding the node before means walking from the head. - Downleveling · also downlevel, downleveled
- Taught in The interview and this lab
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.
- Dummy head · also dummy node, placeholder node
- Taught in Linked lists
A placeholder node made in front of a list,
dummy = ListNode()ordummy = ListNode(0, head), whose value is never used. It gives the first real node a node before it, so attaching (tail.next = node, thentail = tail.next) and removing (before.next = before.next.next) work the same way at the head as anywhere else. The answer isdummy.next. - Dynamic programming · also DP
- Taught in Dynamic programming
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.
- Early return
- Taught in Python, one step at a time
A
returninside 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. - Edge case
- Taught in The interview and this lab
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".
- Edit distance · also Levenshtein distance
- Taught in Dynamic programming
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. - End-of-word mark · also end mark, is_end
- Taught in Heaps and tries
The flag on a trie node that says a stored word ends here: the key
"$"in the dict-of-dicts version,is_endin theTrieNodeclass. 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.searchneeds the mark;starts_withneeds only the node. - Eviction · also evict
- Taught in Linked lists
Removing an entry from a full cache to make room. In an LRU cache it happens only when a
putbrings 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. - Exchange argument
- Taught in Sorting and binary search
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.
- Factorial · also n!
- Taught in Counting steps: Big O
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.
- Fast and slow pointers · also slow and fast pointers, runner technique
- Taught in Linked lists
Two names walking one linked list at different speeds:
slowmoves one node per step andfastmoves two. Whenfastcannot move two more nodes,slowis at position n // 2, the middle (the second of the two middles when n is even). The loop testwhile fast is not None and fast.next is not Nonemakes readingfast.next.nextsafe. The same pair detects a cycle. - First-true template
- Taught in Sorting and binary search
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), loopwhile lo < hi, a yes setshi = mid, a no setslo = mid + 1, thenreturn lo. It returns the length when no index is a yes. - Fixed-gap pointers
- Taught in Linked lists
Two pointers moving at the same speed, one n nodes ahead of the other. Move
fastn nodes first, then move both one node per step. Whenfastwalks off the end,slowis node number n from the end (the last node is number 1). Starting both on a dummy head and stopping whenfastis on the last node leavesslowon the node before that one, ready to remove it. One walk, O(1) extra space. - Fixed-size window · also fixed window
- Taught in Two pointers and sliding windows
A sliding window that always holds the same number of items, k. Each slide adds the item at
rightand removes the item atright - k, and the window then starts atright - 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). - Floor division · also integer division, //
- Taught in Python, one step at a time
a // bdivides and rounds down to a whole number:7 // 2is 3, and-7 // 2is -4, because rounding down moves toward the smaller number. Plain/always gives a float:7 / 2is 3.5 and8 / 2is 4.0. - Floyd's cycle check · also tortoise and hare, Floyd's cycle detection
- Taught in Linked lists
Finding a cycle in a linked list with fast and slow pointers and no other memory. Both start at the head; each step moves
slowone node andfasttwo, then checksslow is fast. Without a cycle,fastreaches the end. With one, the gap fromfastforward toslowshrinks by exactly one node per step once both are in the loop, sofastcannot jump overslow, and they meet. O(n) time and O(1) extra space, where a set of visited nodes costs O(n) space. - Follow-up types · also follow-ups, complexity probe, scale shift, constraint flip, rationale probe
- Taught in The interview and this lab
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?).
- Frame · also frame card, walk, notebook, promise, cost
- Taught in The interview and this lab
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.
- functools.cache · also @cache, cache decorator
- Taught in Dynamic programming
A decorator from the
functoolsmodule. Written as@cacheon the line above adef, 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 likei, not a list. - Generate and filter · also generate and test
- Taught in Backtracking
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.
- Generator expression · also genexp
- Taught in Python, one step at a time
A comprehension inside a call, without its square brackets:
any(x < 0 for x in nums)orsum(x * x for x in nums). It makes the values one at a time, as the call asks for them, soanyandallcan stop at the first value that settles the answer, and the whole list is never built. - Graph
- Taught in Graphs
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.
- Greatest common divisor · also gcd, Euclid's algorithm, Euclidean algorithm
- Taught in Greedy and a little math
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. - Greedy algorithm · also greedy, greedy choice
- Taught in Sorting and binary search
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.
- Grid graph
- Taught in Graphs
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
directionslist 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. - Grouping key
- Taught in Arrays and hash maps
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.
- Growth rate · also time complexity
- Taught in Counting steps: Big O
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).
- Half-open interval
- Taught in Sorting and binary search
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]. - Hamming distance
- Taught in Greedy and a little math
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. - Hash function · also hash
- Taught in Arrays and hash maps
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 ishash(). - Hash map · also hash table
- Taught in Arrays and hash maps
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
dictandsetare 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. - Hashable
- Taught in Arrays and hash maps
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
TypeErrorthat saysunhashable type: 'list'(or'dict', or'set'). To use a list's contents as a key, convert it first withtuple(nums). - Heap · also min-heap, binary heap
- Taught in Heaps and tries
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
iare at2 * i + 1and2 * 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. - heapify · also heapq.heapify, build a heap
- Taught in Heaps and tries
Turning a whole list into a heap in place: sift down every parent, from index
n // 2 - 1back 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)changesnumsitself, so heapify a copy,list(nums), when the caller still needs the original. - heapq · also priority queue, heap queue
- Taught in Heaps and tries
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)addsx,heapq.heappop(heap)removes and returns the smallest,heapq.heapify(nums)rearranges a list into a heap, andheap[0]reads the smallest.heappushandheappopkeep a min-heap. Python 3.14 added max-heap versions such asheappush_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. - Height of a tree · also height, max depth, maximum depth
- Taught in Recursion and trees
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.
- Histogram
- Taught in Stacks and queues
In this course, a bar chart of bars of width 1 standing side by side, where
heights[i]is the height of bari. 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. - Identity check · also is, is not
- Taught in Linked lists
a is basks whether two names lead to the very same object;a == basks whether two values are equal. Two different nodes that both hold 4 have equal values,a.val == b.val, buta is bisFalse. Compare nodes withis, and test forNonewithis Noneoris not None, since there is only oneNoneobject. - Immutable · also immutability
- Taught in Python, one step at a time
Cannot be changed after it is made. Strings, numbers and tuples are immutable.
s[0] = "S"raises aTypeError, 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. - In place
- Taught in Python, one step at a time
Changing an existing list itself instead of building a new one.
nums[1] = 9,nums.append(4)andnums.sort()all work in place, so every name for that list sees the change.appendandsortreturnNone: the changed list is the result. - In-degree
- Taught in Graphs
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.
- Index · also position
- Taught in Python, one step at a time
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 islen(nums) - 1, which is 2. A negative index counts from the end:nums[-1]is 7. - Input size (n) · also n
- Taught in Counting steps: Big O
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.
- Insertion sort
- Taught in Sorting and binary search
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.
- Integer overflow · also overflow
- Taught in Greedy and a little math
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.
- Interval
- Taught in Sorting and binary search
A pair
[start, end]withstart <= 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. - Interval DP · also interval dynamic programming
- Taught in 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. - K-way merge · also merge k sorted lists, heap of fronts
- Taught in Heaps and tries
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. - Kadane's algorithm · also extend or restart, maximum subarray
- Taught in Greedy and a little math
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 largestcurrentseen. O(n) time, O(1) extra space. Start both atnums[0], not 0, so that an all-negative list gets its largest item. - Lambda · also anonymous function
- Taught in Sorting and binary search
A one-line function with no name:
lambda order: order[1]takesorderand returnsorder[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]). - Leap of faith
- Taught in Recursion and trees
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.
- Level-order traversal · also level order, BFS on a tree
- Taught in Recursion and trees
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. - Linked list · also singly linked list
- Taught in Linked lists
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 ofNone. 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. - Linked list cycle
- Taught in Linked lists
A loop in the links: some node's
nextpoints back to an earlier node, or to itself, so a walk that waits forNonenever ends. A cycle means reaching the same node object again, not meeting an equal value, so checks compare nodes withis. - List comprehension · also comprehension
- Taught in Python, one step at a time
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 evenxinnums. Read it from thefor, then theif, then the expression on the left. - ListNode · also list node
- Taught in Linked lists
The node class every lab cell already has, the same one LeetCode uses:
ListNode(val, next).valis the value the node holds andnextis the node after it, orNoneafter the last node.nextis a pointer, also called a link: it leads to the next node itself, not a copy of its value.cur = cur.nextmoves the namecuralong the list;cur.next = otherchanges the list. - Load factor
- Taught in Arrays and hash maps
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.
- Log scale
- Taught in Counting steps: Big O
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.
- Logarithm · also log n, base-2 logarithm
- Taught in Counting steps: Big O
is the power you raise 2 to in order to get n: 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 times, rounded down: 19 passes for a million items. In this course, log n means log base 2.
- Longest common subsequence · also LCS
- Taught in Dynamic programming
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 cellbest[i][j]holds the answer for the firstiletters of one and the firstjof 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. - Longest increasing subsequence · also LIS
- Taught in Dynamic programming
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 largestends_here[j]over earlier, smaller items, and the answer is the largest cell, in O(n2) time. A sortedtailslist with binary search (patience sorting) finds the length in O(n log n). - Lowest 1 bit · also lowest set bit, x & (x - 1)
- Taught in Greedy and a little math
The rightmost 1 in a number's binary form.
x & (x - 1)isxwith 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 is101100and 43 is101011, so44 & 43is101000, which is 40. Repeating it untilxis 0 counts the 1 bits, one pass per 1. - Lowest common ancestor · also LCA
- Taught in Recursion and trees
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). - LRU cache · also least recently used cache
- Taught in Linked lists
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
getthat finds its key, or anyput. A dict from key to node plus a doubly linked list of the nodes in order of use makesgetandputO(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. - Mark and unmark · also in-place marking
- Taught in Backtracking
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. - Max-heap · also max heap
- Taught in Heaps and tries
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). - Memoization · also memo, memoize
- Taught in Recursion and trees
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. - Memory address · also address
- Taught in Arrays and hash maps
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). - Merge from the back
- Taught in Two pointers and sliding windows
Merging two sorted lists into the first one, when its free room is at the end: start with
writeat 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, becausewritealways equalsi + j + 1. O(m + n) time, O(1) extra space. - Merge sort
- Taught in Sorting and binary search
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.
- Merging sorted lists · also merge
- Taught in Sorting and binary search
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.
- Min stack
- Taught in Stacks and queues
A stack that can also report its smallest value in O(1). Each value is stored as a pair
(value, smallest), wheresmallestis 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. - Miss types · also error journal, knowledge gap, careless miss, concept miss, procedure miss
- Taught in The interview and this lab
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.
- Mixed practice · also interleaved practice, interleaving, mixed set
- Taught in The interview and this lab
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.
- Mock round · also mock, mock interview
- Taught in The interview and this lab
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.
- Modulo · also mod, remainder, %
- Taught in Python, one step at a time
a % bis the remainder left aftera // b:17 % 5is 2, because 5 fits into 17 three times with 2 left over.x % 2 == 0asks whetherxis even, andn % 10is the last digit of a positiven. - Monotonic deque
- Taught in Stacks and queues
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).
- Monotonic stack
- Taught in Stacks and queues
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).
- Multi-part build · also escalating build
- Taught in Interview mode
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.
- Multi-source BFS · also multi-source breadth-first search
- Taught in Graphs
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.
- N-Queens · also eight queens
- Taught in Backtracking
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 - colandrow + col. For n = 8 there are 92 placements, found in 2,057 calls. - Next greater element
- Taught in Stacks and queues
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. - No-execution checklist · also self-test checklist
- Taught in Interview mode
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
Noneand 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. - None
- Taught in Python, one step at a time
Python's value for "no value", the job
NULLdoes in a table. A function that ends without areturnhands backNone, one of the most common reasons a first solution fails its tests. - None path · also not-found path
- Taught in Interview mode
A way through the code on which a name can hold
None: an empty linked list or tree, thenextof the last node, a child of a leaf. Any.next,.left,.rightor.valread 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 backNonewhen the loop ends without a match. - nonlocal
- Taught in Recursion and trees
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 tobestinside the inner function makesbesta new name of the inner function, and reading it before that assignment raisesUnboundLocalError. Reading an outer name, or changing the list or dict it points at (out.append(x),memo[k] = v), needs nononlocal. - Notebook
- Taught in The interview and this lab
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. - Off-by-one error · also off-by-one, off by one
- Taught in Python, one step at a time
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)givesaup tob - 1, so check the first and last value of every loop variable. - Operand
- Taught in Stacks and queues
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. - OrderedDict · also collections.OrderedDict
- Taught in Linked lists
A dict from
collectionsthat remembers the order of its keys and reorders them in O(1):move_to_end(key)sends a key to the back, andpopitem(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. - Palindrome
- Taught in Two pointers and sliding windows
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. - Permutation · also ordering, arrangement
- Taught in Backtracking
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. - Pointer · also link
- Taught in Linked lists
A reference that leads to another object instead of holding a copy of it: a node's
nextpoints 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. - Postfix notation · also reverse Polish notation, RPN
- Taught in Stacks and queues
A way to write arithmetic where each operator comes after the two values it combines, not between them:
2 3 +means 2 + 3, and2 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. - Power of two
- Taught in Greedy and a little math
One of 1, 2, 4, 8, 16 and so on: a number with exactly one 1 bit. So
x > 0 and x & (x - 1) == 0tests for one. Thex > 0part matters, because0 & -1is also 0. - Prefix maxima · also prefix max, running maximum list
- Taught in Interview mode
A list whose position
iholds the largest item from the start up toi: 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 withmaxin place of+, and it finds every bar's left wall in trapping rain water. - Prefix product · also suffix product, suffix
- Taught in Arrays and hash maps
The product of the items before position
i, writtenbefore[i]. A product of nothing is 1, sobefore[0]is 1. The suffix productafter[i]is the product of the items afteri; a suffix is a run that ends at the last item. One walk from the left fillsbefore, one walk from the right fillsafter, andbefore[i] * after[i]is the product of every item exceptnums[i], with no division. - Prefix sum · also prefix sums, cumulative sum
- Taught in Arrays and hash maps
A list where
prefix[i]is the sum of the firstiitems, withprefix[0] = 0, so it is one longer than the list. Built in one walk, it turns the sum of positionslefttorightinto one subtraction:prefix[right + 1] - prefix[left]. - Preorder, inorder and postorder · also preorder, inorder, postorder, depth-first traversal
- Taught in Recursion and trees
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.
- Promise · also invariant, loop invariant
- Taught in The interview and this lab
A sentence about the notebook that is true after every step of the walk. For a running maximum: after each pass,
bestis 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. - Pruning · also prune test, cutting a branch
- Taught in Backtracking
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).
- Push, pop and peek · also top of the stack
- Taught in Stacks and queues
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 checkif stack:first when the stack could be empty. - Queue · also FIFO, first in, first out
- Taught in Stacks and queues
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:
appendto join,popleft()to leave, both O(1).list.pop(0)gives the same order but costs O(n). - Re-solve ladder · also spaced practice, spacing, re-solve schedule
- Taught in The interview and this lab
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.
- Read and write pointers · also read pointer, write pointer
- Taught in Two pointers and sliding windows
Two indexes that walk one list in the same direction to edit it in place.
readvisits every item once;writeis the slot where the next kept item goes. The promise:nums[:write]is the finished answer for the items read so far. Becausewritenever passesread, 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. - Recurrence · also recurrence relation
- Taught in Dynamic programming
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), withways(0) = ways(1) = 1. - Recursion · also recursive function
- Taught in Recursion and trees
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 whenn <= 1andn * factorial(n - 1)otherwise. Trees have the same shape: a node with smaller trees under it. - Recursion limit · also RecursionError, maximum recursion depth
- Taught in Recursion and trees
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, andsys.setrecursionlimitraises 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. - Reference
- Taught in Arrays and hash maps
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
7or at a long string. Repeating a reference shares one value:[[0] * 3] * 2makes two slots that point at the same row. - Rehashing · also resizing a hash table
- Taught in Arrays and hash maps
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 % 8is not alwayskey % 4. It costs O(n) for that one add, but it is rare enough that adds stay amortized O(1). - Repeated work
- Taught in Interview mode
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).
- Retrieval practice · also retrieval
- Taught in The interview and this lab
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.
- Reversing a linked list · also in-place reversal
- Taught in Linked lists
Pointing every
nextthe other way without making new nodes. Walk with three names:prev, the head of the part already reversed (at firstNone);cur, the node we are on; andnxt, the rest of the list. Each pass saves, flips, then moves:nxt = cur.next,cur.next = prev,prev = cur,cur = nxt. WhencurisNone,previs the new head. O(n) time, O(1) extra space. - Rotated sorted list · also rotated sorted array
- Taught in Sorting and binary search
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. - Running total, count and maximum · also running total, running count, running maximum, running max
- Taught in Python, one step at a time
A loop's notebook of one value, updated once per item, with a promise that holds after every pass:
totalis the sum of the items visited so far,countis how many of them passed a test,bestis the largest so far. When the walk ends, the promise is the answer. Start a running maximum atnums[0]orfloat("-inf"), not at 0, unless every value is known to be 0 or more:best = 0gives 0 for[-6, -3, -8]. - Saving a copy of the path · also path[:], snapshot of the path
- Taught in Backtracking
At a leaf, save
path[:](orlist(path)), a new list holding whatpathholds right now, notpathitself. Backtracking keeps changing one sharedpath, and it ends empty, soresult.append(path)would save that one list again and again (aliasing). A string built with"".join(path)is already a new value. - Seating values in place · also list as its own hash map, cyclic sort
- Taught in Interview mode
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.
- Seen-before · also seen set
- Taught in Arrays and hash maps
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 - xinstead ofx, with a dict of positions, it solves two sum. - Sentinel node · also sentinel
- Taught in Linked lists
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,
headbefore the oldest node andtailafter the newest; an empty list is the two sentinels pointing at each other. Every real node then has a node on both sides, neverNone, so unlinking and appending need no special cases. A dummy head is a sentinel at the front. - Short-circuiting · also short-circuit evaluation
- Taught in Python, one step at a time
andstops at the first false side andorstops 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] > 0never readsnums[i]wheniis past the end. - Sift down · also bubble down
- Taught in Heaps and tries
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).
- Sift up · also bubble up
- Taught in Heaps and tries
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).
- Signal · also problem signal
- Taught in Interview mode
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.
- Slice
- Taught in Python, one step at a time
A new list or string cut from neighboring positions.
nums[start:stop]includesstart, stops beforestop, and holdsstop - startitems: withnums = [12, 30, 7, 25],nums[1:3]is[30, 7].nums[:]slices everything, which makes a copy. - Sliding window · also window, rolling window
- Taught in Two pointers and sliding windows
A block of consecutive items in a list or string, from index
leftto indexright, 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. - Space complexity · also extra space
- Taught in Counting steps: Big O
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.
- Stable sort · also stability
- Taught in Sorting and binary search
A sort that keeps items with equal keys in the order they had before the sort. Python's
sortedandlist.sortare stable, also withreverse=True: sorting[("cy", 30), ("ana", 30)]by amount keeps"cy"first. - Stack · also LIFO, last in, first out
- Taught in Stacks and queues
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:
appendadds to the top andpop()removes from it, both O(1) (appendamortized). Reach for one when the newest unfinished item is the one you need next, as with nested brackets or an Undo button. - Start index · also start parameter
- Taught in Backtracking
An argument, often
start, that lets a backtracking call try only the choices at indexstartor later, so each combination is built once instead of once per order. Passingito the next call lets the same item come again; passingi + 1uses each item at most once. With sorted choices, a choice that is too big canbreakthe loop, because every later one is bigger. - State · also DP state
- Taught in Dynamic programming
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 firstihouses". The state is what the rest of the problem needs to know about the choices already made, and nothing more: for painting houses, the houseiand the color it got, not the money spent so far. - Step
- Taught in Counting steps: Big O
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.
- Struggle cap
- Taught in The interview and this lab
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.
- Stuck recovery script · also recovery script
- Taught in Interview mode
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.
- Subarray · also contiguous subarray
- Taught in Arrays and hash maps
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. - Subproblem · also overlapping subproblems
- Taught in Dynamic programming
A smaller version of the problem being solved, such as
fib(3)insidefib(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. - Subsequence
- Taught in Dynamic programming
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. - Subset sum
- Taught in Dynamic programming
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.
- Substring
- Taught in Two pointers and sliding windows
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 fromlefttoright, both included. - Sum of 1 to n · also n(n + 1) / 2
- Taught in Greedy and a little math
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) // 2stays a whole number. The missing number problem compares this expected total with the actual one. - Sweep line · also line sweep
- Taught in Sorting and binary search
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.
- Switches once · also monotonic
- Taught in Sorting and binary search
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.
- Think-aloud script · also live-round protocol, clarify, plan, implement, test, summarize
- Taught in Interview mode
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.
- Tiebreaker
- Taught in Heaps and tries
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 twoListNodes cannot be ordered, and comparing them raisesTypeError. - Timsort
- Taught in Sorting and binary search
The sort behind Python's
sortedandlist.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. - Tombstone · also delete marker
- Taught in Interview mode
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. - Top k with a heap · also k largest, kth largest, top-N
- Taught in Heaps and tries
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. - Top-down · also top-down DP, memoized recursion
- Taught in Dynamic programming
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.
- Topological order · also topological sort
- Taught in Graphs
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.
- Trace · also tracing, hand trace, dry run
- Taught in The interview and this lab
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.
- Traceback · also stack trace
- Taught in Python, one step at a time
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.
- Transaction
- Taught in Interview mode
A group of changes kept or undone as a whole.
beginopens one,commitkeeps every change made since, androllbackundoes them all, so the store returns to how it stood atbegin. In SQL these areBEGIN,COMMITandROLLBACK. - Transition · also transition rule
- Taught in Dynamic programming
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. - TreeNode · also tree node
- Taught in Recursion and trees
The tree node class every lab cell already has, the same one LeetCode uses:
TreeNode(val, left, right), whereleftandrightare its children, orNonewhen missing.build_treemakes a tree from a list in level order: the root, then each level from left to right, withNonefor a missing child. Every real node takes the next two values as its children, and aNonetakes none.tree_valuesturns a tree back into that list. - Trie · also prefix tree
- Taught in Heaps and tries
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.
- TrieNode · also trie node
- Taught in Heaps and tries
The class version of a trie node:
self.children = {}maps each next letter to its childTrieNode, andself.is_end = Falseturns True where a stored word ends. Createchildreninside__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. - Two pointers · also pointers from both ends, left and right pointers
- Taught in Two pointers and sliding windows
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,
leftstarts at position 0 andrightat the last position, and they move toward each other whileleft < 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). - Two-heap median · also running median, median of a stream
- Taught in Heaps and tries
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, andhigh, a min-heap of the larger half. Every number inlowis at most every number inhigh, andlowholds as many numbers ashighor 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). - Two-stack queue · also queue from two stacks
- Taught in Stacks and queues
A queue built from two stacks. New items are pushed onto
in_stack. When the front is needed andout_stackis empty, every item moves fromin_stacktoout_stack, which reverses them so the oldest is on top. Each item moves at most once, sopopis O(1) amortized even though one call can move every item. - Undo record
- Taught in Interview mode
For one open transaction, a dict from each key it changed to the value that key held before the transaction first changed it (
Noneif 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. - Union by size and path compression
- Taught in Graphs
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).
- Union-find · also disjoint set union, DSU
- Taught in Graphs
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, andunion(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. - Unpacking · also tuple unpacking
- Taught in Python, one step at a time
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 swapa, b = b, a, two return values withreturn low, high, and loops such asfor i, x in enumerate(nums). - Used list · also used array, used flags
- Taught in Backtracking
A list of booleans, one per position, where
used[i]isTruewhileitems[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. - Variable · also name
- Taught in Python, one step at a time
A name tied to a value, like a tag.
x = 5works out the right side first, then ties the namexto 5. A laterx = x + 1moves the tag to a new value (this is called rebinding); the old value itself never changes. - Variable window · also variable-size window, window that grows and shrinks
- Taught in Two pointers and sliding windows
A sliding window whose size changes.
rightmoves one step every pass; while the window breaks the rule,leftmoves 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 awhileloop inside theforloop. 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. - Walk
- Taught in The interview and this lab
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. - Wildcard search · also dot search, pattern search
- Taught in Heaps and tries
Matching a pattern in which a dot stands for any one letter, such as "c.t", against the words in a trie. A letter follows its one child. A dot tries every child, depth first: return True as soon as one branch matches, and False only after every branch has failed. Each dot can multiply the paths by up to 26, so the number of dots, not the number of stored words, decides the cost.
- Worst case
- Taught in Counting steps: Big O
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.
- XOR · also ^, exclusive or
- Taught in Greedy and a little math
Exclusive or, written
^in Python: a 1 where the two bits differ, a 0 where they match.x ^ xis 0,x ^ 0isx, 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 ^ 3is 1, while2 ** 3is 8.