cswork / templatesOpen the Line 500 list

GLOSSARY · 187 TERMS · CHINESE / ENGLISH

The words for explaining your solution.

187 algorithm and data structure terms in Chinese and English, each with an interview sentence you can listen to and turn into a review card.

To print every stop’s template, use the printable handbook.

187 terms

Basics & complexity 32

时间复杂度time complexity
The time complexity is O(n log n), and the sort is the slowest step.
空间复杂度space complexity
The hash map makes the space complexity O(n); with two pointers I could bring it down to O(1).
大 O 表示法Big O notation
Also: big-O
Big O notation drops constants, so two n plus five is still O(n).
均摊复杂度amortized time
Also: amortized complexity · amortized O(1)
Appending to a dynamic array is amortized O(1), even though an occasional resize costs O(n).
暴力解法brute force
Also: naive approach
Let me start with a brute force solution that checks every pair, and then optimize it.
边界情况edge case
Also: corner case
One edge case is an empty array, so I return zero right away.
差一错误off-by-one error
Let me double-check the loop bound so I don't make an off-by-one error.
整数溢出integer overflow
The sum can pass two billion, so I use a 64-bit integer to avoid integer overflow.
数据范围constraints
Also: input size
The constraints say n can be a hundred thousand, so an O(n squared) solution would time out.
超时Time Limit Exceeded
Also: TLE
My first version got TLE on the large tests, so I replaced the nested loop with a hash set.
答案错误Wrong Answer
Also: WA
It passes the samples but gets Wrong Answer, which points to an edge case I missed.
超内存Memory Limit Exceeded
Also: MLE
The full table hit Memory Limit Exceeded, so I compressed it to a single row.
Template: Grid DP
运行错误runtime error
The runtime error came from reading one index past the end of the array.
测试用例test case
Let me walk through a small test case to make sure the logic holds.
手动模拟(走一遍样例)dry run
Also: walk through · trace
Before running it, let me do a dry run with the input one, three, two.
伪代码pseudocode
I'll sketch the pseudocode first and then turn it into real code.
递归recursion
Also: recursive
Recursion fits here because each subtree is the same problem, only smaller.
Template: Tree Traversal
递归出口base case
Also: termination condition
The base case is a null node, which returns zero.
Template: Tree Traversal
调用栈call stack
Also: stack overflow
If the tree is one long chain, the call stack could get too deep, so I'll write it iteratively.
迭代写法iterative approach
Also: iteratively
An iterative approach with an explicit stack avoids deep recursion.
循环不变量loop invariant
Also: invariant
The loop invariant is that everything left of lo is false and everything from hi on is true.
Template: Binary Search
权衡(取舍)trade-off
Also: tradeoff
The trade-off is extra memory for the hash map in exchange for linear time.
分治divide and conquer
Merge sort is divide and conquer: split the array, sort each half, then merge them.
模拟simulation
Also: simulate
There's no trick here; it's a simulation, so I'll follow the rules step by step.
预处理preprocessing
Also: precompute
With some preprocessing I can precompute prefix sums and answer each query in O(1).
稳定排序stable sort
I need a stable sort so that equal keys keep their original order.
自定义比较器comparator
Also: custom comparator · sort key
I'll pass a custom comparator that sorts by end time, then by start time.
计数排序counting sort
The values are between zero and one hundred, so counting sort runs in linear time.
升序 / 降序ascending order
Also: descending order · non-decreasing
I sort the array in ascending order and scan it from the left.
字典序lexicographic order
Also: lexicographical order · lexicographically smallest
They want the lexicographically smallest answer, so at each step I pick the smallest valid character.
离线查询offline queries
Also: offline algorithm
All the queries are known up front, so I can sort them and answer them as offline queries.
哨兵sentinel value
Also: sentinel
I append a sentinel value of infinity so the last group is closed inside the loop.

Arrays & strings 24

双指针two pointers
The array is sorted, so I can use two pointers that move toward each other.
Template: Two Pointers
读写指针(快慢下标)read and write pointers
With read and write pointers, everything to the left of the write pointer is already final.
Template: In-place Arrays
原地修改in-place
Also: in place
I'll do it in place by overwriting the array, so the extra space is O(1).
Template: In-place Arrays
荷兰国旗问题(三路划分)Dutch national flag
Also: three-way partition
This is the Dutch national flag problem: one pass with three pointers sorts the zeros, ones and twos.
Template: In-place Arrays
滑动窗口sliding window
I keep a sliding window and shrink it from the left whenever it contains a repeated character.
Template: Two Pointers
定长滑窗fixed-size window
For a fixed-size window of k, I add the new element and drop the one that falls out.
Template: Two Pointers
前缀和prefix sum
Also: cumulative sum · running sum
With a prefix sum array, any range sum is the difference of two entries.
Template: Prefix & Ranges
差分difference array
For many range updates, a difference array adds v at l and subtracts v at r plus one; one prefix sum then rebuilds the values.
Template: Prefix & Ranges
二维前缀和2D prefix sum
Also: summed-area table
A 2D prefix sum gives any rectangle's sum in O(1) with inclusion-exclusion.
Template: Prefix & Ranges
区间合并merge intervals
Also: overlapping intervals
To merge intervals, I sort them by start and extend the last one while the next one starts no later than it ends.
Template: Prefix & Ranges
扫描线sweep line
Also: line sweep
A sweep line over the sorted start and end events tells me how many meetings overlap at once.
Template: Prefix & Ranges
子数组subarray
A subarray has to be contiguous, unlike a subsequence.
Template: Prefix & Ranges
子序列subsequence
A subsequence keeps the relative order, but its elements don't have to be next to each other.
Template: Subsequences
子串substring
I'm looking for the longest substring without repeating characters.
Template: Two Pointers
回文palindrome
Also: palindromic
To find the longest palindrome, I expand around each center.
Template: Palindromes
字母异位词anagram
Two words are anagrams when their letter counts match, so I compare the count arrays.
Template: Hashing
频次统计frequency map
Also: frequency count · counter
I build a frequency map of the characters in one pass.
Template: Hashing
KMP 算法KMP algorithm
Also: Knuth-Morris-Pratt · prefix function
KMP never moves the text pointer back; on a mismatch it falls back using the prefix function.
Template: Strings
字符串哈希(滚动哈希)rolling hash
Also: Rabin-Karp · string hashing
A rolling hash lets me compare two substrings in O(1) after linear preprocessing.
Template: Strings
字符串拼接string builder
Also: immutable string
Strings are immutable in Java, so I use a string builder instead of concatenating in a loop.
Template: Strings
数组越界out of bounds
Also: index out of range
I check that r plus one is less than n first, so the access never goes out of bounds.
螺旋遍历spiral order
I peel the matrix layer by layer to read it in spiral order.
快速选择quickselect
Quickselect finds the k-th largest element in average O(n) time without sorting everything.
Template: Stacks & Heaps
离散化coordinate compression
Also: discretization
The values go up to a billion, so I use coordinate compression to map them to their ranks.

Data structures 28

哈希表hash map
Also: hash table · dictionary
A hash map from value to index gives me O(1) average lookups.
Template: Hashing
哈希集合hash set
I store the values I've seen in a hash set to catch duplicates.
Template: Hashing
哈希冲突hash collision
With many hash collisions, a single lookup can degrade to O(n).
Template: Hashing
栈stack
Also: last in, first out · LIFO
A stack fits here because the most recent open bracket has to close first.
Template: Stacks & Heaps
队列queue
Also: first in, first out · FIFO
BFS uses a queue, so nodes are processed in the order they were found.
Template: Tree Traversal
双端队列deque
Also: double-ended queue
A deque, pronounced like deck, lets me push and pop at both ends in O(1).
Template: Stacks & Heaps
单调栈monotonic stack
A monotonic stack finds the next greater element for every index in one pass.
Template: Stacks & Heaps
单调队列monotonic queue
Also: monotonic deque
A monotonic queue gives the maximum of every window in O(n) total.
Template: Stacks & Heaps
堆(优先队列)heap
Also: priority queue · min-heap · max-heap
I keep a min-heap of size k, so its top is always the k-th largest so far.
Template: Stacks & Heaps
懒删除lazy deletion
Instead of decrease-key, I use lazy deletion: push the new distance and skip stale entries when they pop.
Template: Shortest Paths
链表linked list
Reversing a linked list in place only needs three pointers.
Template: Linked Lists
虚拟头节点(哑节点)dummy node
Also: dummy head · sentinel node
A dummy node before the head means removing the head is not a special case.
Template: Linked Lists
快慢指针fast and slow pointers
Also: tortoise and hare · Floyd's cycle detection
With fast and slow pointers, the fast one takes two steps at a time, so they meet if there's a cycle.
Template: Linked Lists
双向链表doubly linked list
The cache pairs a hash map with a doubly linked list, so moving a node to the front is O(1).
Template: Caches
LRU 缓存LRU cache
Also: least recently used
When it's full, an LRU cache evicts the least recently used key.
Template: Caches
字典树(前缀树)trie
Also: prefix tree
A trie, usually pronounced like try, stores words by prefix, so a lookup costs only the word's length.
Template: Trie & Codec
序列化serialization
Also: serialize · deserialize
For serialization, I write the tree in preorder with a marker for each null child.
Template: Trie & Codec
迭代器iterator
Also: lazy iterator
The iterator does its work in hasNext, so next only returns the value it found.
Template: Iterators
并查集union-find
Also: disjoint set union · DSU · disjoint-set
With union-find, I join the two ends of each edge, and an edge whose ends are already connected closes a cycle.
Template: Union-Find
路径压缩path compression
Path compression flattens the tree during find, so later finds are almost constant time.
Template: Union-Find
按秩合并(按大小合并)union by size
Also: union by rank
Union by size hangs the smaller tree under the larger one, which keeps the trees shallow.
Template: Union-Find
线段树segment tree
A segment tree supports range sum queries and point updates in O(log n).
懒标记(延迟传播)lazy propagation
Also: lazy tag
With lazy propagation, a range update stops at fully covered nodes and pushes the change down later.
树状数组Fenwick tree
Also: binary indexed tree · BIT
A Fenwick tree, also called a binary indexed tree, handles prefix sums with updates in O(log n).
ST 表(稀疏表)sparse table
A sparse table answers range minimum queries in O(1) after O(n log n) preprocessing.
有序集合ordered set
Also: TreeMap · sorted container · balanced BST
In Java I'd use a TreeMap to find the floor and ceiling keys in O(log n).
Template: BST
动态数组dynamic array
Also: ArrayList · vector
A dynamic array doubles its capacity when it fills up.
环形数组(循环队列)circular buffer
Also: ring buffer
A circular buffer reuses a fixed array and wraps the index around with modulo.

Trees & graphs 36

二叉树binary tree
In a binary tree, every node has at most two children.
Template: Tree Traversal
子树subtree
Each recursive call returns one piece of information about its subtree.
Template: Tree Traversal
叶子节点leaf node
Also: leaf
A root-to-leaf path ends at a leaf node, a node with no children.
Template: Tree Paths
树的高度(深度)height
Also: depth · max depth
The height of a node is one plus the larger height of its two children.
Template: Tree Traversal
平衡二叉树balanced binary tree
Also: height-balanced
A balanced binary tree keeps its height at O(log n), so searches stay fast.
Template: BST
二叉搜索树binary search tree
Also: BST
In a binary search tree, every value in the left subtree is smaller than the node.
Template: BST
前序遍历preorder traversal
Also: pre-order
In a preorder traversal the root comes first, so the first value is the root.
Template: Tree Building
中序遍历inorder traversal
Also: in-order
I'll do an iterative inorder traversal with a stack and stop at the k-th node.
Template: BST
后序遍历postorder traversal
Also: post-order
A postorder traversal fits, because each node needs its children's results first.
Template: Tree Paths
层序遍历level-order traversal
Also: level order
For a level-order traversal, I record the queue size at the start of each level.
Template: Tree Traversal
最近公共祖先lowest common ancestor
Also: LCA
The lowest common ancestor is the deepest node that has both p and q in its subtree.
Template: Tree Paths
树的直径diameter of a tree
Also: tree diameter
The diameter of a tree is its longest path between two nodes, and it doesn't have to pass through the root.
Template: Tree Paths
顶点和边vertices and edges
Also: vertex · edge
With V vertices and E edges, BFS runs in O(V plus E).
有向图 / 无向图directed graph
Also: undirected graph
The prerequisites form a directed graph, with an edge from each course to the courses it unlocks.
Template: Topo Sort
带权图weighted graph
Also: edge weight
In a weighted graph, the path with the fewest edges isn't always the cheapest.
Template: Shortest Paths
邻接表adjacency list
Also: adjacency matrix
The graph is sparse, so I'll build an adjacency list.
入度 / 出度in-degree
Also: out-degree · indegree
A node with an in-degree of zero has no prerequisites left, so it goes into the queue.
Template: Topo Sort
有向无环图directed acyclic graph
Also: DAG
It's a DAG, so I can run the DP in topological order.
Template: Topo Sort
广度优先搜索(广搜)breadth-first search
Also: BFS
Breadth-first search finds the shortest path when every edge has the same cost.
Template: Grid Search
深度优先搜索(深搜)depth-first search
Also: DFS
I run a depth-first search from each unvisited land cell to count the islands.
Template: Grid Search
多源 BFSmulti-source BFS
With multi-source BFS, every starting cell goes into the queue at time zero.
Template: Grid Search
双向 BFSbidirectional BFS
Bidirectional BFS searches from both ends and stops when the two frontiers meet.
Template: Grid Search
访问标记visited set
Also: mark as visited
I add a cell to the visited set when it's enqueued, so it never enters the queue twice.
Template: Grid Search
洪水填充(泛洪)flood fill
Flood fill spreads from the start cell to every connected cell of the same color.
Template: Grid Search
连通分量(连通块)connected component
Also: connected components
Each DFS from an unvisited node covers exactly one connected component.
Template: Union-Find
判环cycle detection
Also: detect a cycle
For cycle detection in a directed graph, a DFS that reaches a node still on the current path has found a cycle.
Template: Topo Sort
拓扑排序topological sort
Also: topological order · Kahn's algorithm
A topological sort exists only when the graph has no cycle, which is the whole course schedule check.
Template: Topo Sort
二分图bipartite graph
Also: two-coloring
A bipartite graph can be two-colored so that no edge joins two nodes of the same color.
最短路shortest path
With equal edge costs BFS gives the shortest path; with non-negative weights I need Dijkstra.
Template: Shortest Paths
Dijkstra 算法Dijkstra's algorithm
Also: Dijkstra
Dijkstra's algorithm, said DIKE-struh, only works when every edge weight is non-negative.
Template: Shortest Paths
Bellman-Ford 算法Bellman-Ford
Also: negative cycle
Bellman-Ford handles negative edge weights and can detect a negative cycle.
Template: Shortest Paths
Floyd 算法(多源最短路)Floyd-Warshall
Also: all-pairs shortest paths
Floyd-Warshall computes all-pairs shortest paths in O(n cubed), which is fine for a hundred nodes.
Template: Shortest Paths
0-1 BFS(双端队列广搜)0-1 BFS
Also: deque BFS
With weights of only zero and one, 0-1 BFS pushes a node reached by a zero-weight edge to the front of a deque.
Template: Shortest Paths
最小生成树minimum spanning tree
Also: MST
A minimum spanning tree connects all n nodes with n minus one edges of the least total weight.
Template: Spanning Trees
Kruskal 算法Kruskal's algorithm
Kruskal's algorithm sorts the edges by weight and keeps each one that joins two components.
Template: Spanning Trees
Prim 算法Prim's algorithm
On a dense graph, Prim's algorithm with a plain array runs in O(n squared).
Template: Spanning Trees

Dynamic programming 27

动态规划dynamic programming
Also: DP
Dynamic programming works here because the subproblems overlap and the best answer builds on smaller ones.
Template: DP Basics
状态定义state definition
Also: DP state
My state definition is: dp of i is the best total using the first i houses.
Template: DP Basics
状态转移方程state transition
Also: recurrence · transition
The state transition takes the better of skipping house i or robbing it on top of dp of i minus two.
Template: DP Basics
重叠子问题overlapping subproblems
Plain recursion solves the same calls again and again; these overlapping subproblems are why caching helps.
Template: DP Basics
最优子结构optimal substructure
The problem has optimal substructure: the best path to a cell extends the best path to one of its neighbors.
Template: Grid DP
记忆化搜索memoization
Also: memoize · top-down
Memoization, from the word memo, caches each recursive call by its arguments.
Template: DP Basics
递推(自底向上)bottom-up tabulation
Also: bottom-up · tabulation
Bottom-up tabulation fills the table from the smallest subproblems, so there's no recursion at all.
Template: DP Basics
滚动数组rolling array
Also: rolling variables · space optimization
Each row only needs the one above it, so a rolling array cuts the space to O(n).
Template: Grid DP
方案数number of ways
Also: count the ways
The number of ways can be huge, so I return it modulo ten to the ninth plus seven.
Template: DP Basics
DP 表DP table
I pad the DP table with an extra row and column for the empty prefix.
Template: String DP
网格 DPgrid DP
In this grid DP, each cell depends only on the cell above it and the cell to its left.
Template: Grid DP
0-1 背包0/1 knapsack
Also: zero-one knapsack
In the 0/1 knapsack I loop the capacity downward, so each item is used at most once.
Template: Knapsack
完全背包unbounded knapsack
Coin change is an unbounded knapsack, since each coin can be used any number of times.
Template: Knapsack
伪多项式时间pseudo-polynomial time
The knapsack DP runs in pseudo-polynomial time: it depends on the capacity's value, not on its number of digits.
Template: Knapsack
最长递增子序列longest increasing subsequence
Also: LIS
The longest increasing subsequence takes O(n log n) with a tails array and binary search.
Template: Subsequences
最长公共子序列longest common subsequence
Also: LCS
For the longest common subsequence, matching last characters add one to the diagonal cell.
Template: String DP
编辑距离edit distance
Also: Levenshtein distance
Edit distance takes the cheapest of insert, delete and replace at each cell.
Template: String DP
区间 DPinterval DP
Also: range DP
Interval DP needs the shorter ranges first, so I loop the left end backwards.
Template: Palindromes
Kadane 算法(最大子数组和)Kadane's algorithm
Also: maximum subarray
Kadane's algorithm either extends the current run or restarts at the current element.
Template: State Machines
状态机 DPstate machine DP
With state machine DP, each day has a holding state and a not-holding state.
Template: State Machines
冷冻期cooldown
After selling there's a one-day cooldown, so I add a third state.
Template: Stock Trading
带权区间调度weighted interval scheduling
Weighted interval scheduling sorts the jobs by end time and binary searches for the last compatible one.
Template: Scheduling DP
树形 DPtree DP
In tree DP, each node returns two values: the best with it taken and the best without it.
Template: Tree & Game DP
换根 DPrerooting
Also: rerooting DP · re-rooting
With rerooting, I solve for one root, then move the root to each neighbor and update the answer in O(1).
Template: Tree & Game DP
博弈 DPgame DP
Also: minimax · score difference
In this game DP, each range stores the best score difference the player to move can force.
Template: Tree & Game DP
状压 DP(状态压缩)bitmask DP
Also: DP over subsets
With at most sixteen tasks, bitmask DP keeps the set of finished tasks in one integer.
Template: Bits & Math
数位 DPdigit DP
Digit DP counts the numbers up to n by walking its digits with a flag for whether we're still tight.
二分答案binary search on the answer
Also: binary search the answer
I'll binary search on the answer: guess a speed, then check in O(n) whether it's fast enough.
Template: Binary Search
单调性monotonicity
Also: monotonic
The check is monotonic: if one capacity works, every larger capacity works too.
Template: Binary Search
左闭右开区间half-open interval
Also: inclusive · exclusive
I use a half-open interval, inclusive at lo and exclusive at hi, so the loop runs while lo is less than hi.
Template: Binary Search
第一个大于等于 x 的位置lower bound
Also: bisect_left
Lower bound returns the first index whose value is at least the target.
Template: Binary Search
回溯backtracking
Backtracking builds the answer one choice at a time and undoes each choice after the recursive call.
Template: Enumeration
递归树(决策树)recursion tree
Also: decision tree
Drawing the recursion tree shows that each level picks one more element.
Template: Enumeration
枚举enumeration
Also: enumerate
With n at most twenty, I can enumerate every subset with a bitmask.
Template: Enumeration
排列permutation
Also: permutations
There are n factorial permutations, so this only works for small n.
Template: Enumeration
组合combination
Also: combinations
For combinations, the next level starts from i plus one, so no set is counted twice.
Template: Enumeration
子集subset
Also: power set
Each element is either in the subset or not, which gives two to the n subsets.
Template: Enumeration
同层去重skip duplicates
Also: deduplicate
After sorting, I skip duplicates on the same level when a value equals the one just before it.
Template: Enumeration
切分(分割回溯)partitioning
Also: cut points
For palindrome partitioning, each level of the search decides where the next piece ends.
Template: Partitioning
剪枝pruning
Also: prune
With the candidates sorted, I can prune the rest of the loop once the sum passes the target.
Template: Pruning
搜索空间search space
Placing one queen per row shrinks the search space to n choices per row.
Template: Pruning
N 皇后N-Queens
For N-Queens I track the used columns and both diagonals in three sets.
Template: Pruning
折半搜索meet in the middle
With forty items, meet in the middle splits them into two halves of twenty and combines the two lists of sums.
贪心greedy
Also: greedy algorithm · greedy choice
A greedy choice works here: always take the meeting that ends first.
Template: Greedy
交换论证exchange argument
An exchange argument proves it: swapping an optimal answer's first pick for the earliest-ending interval never makes it worse.
Template: Greedy
区间调度interval scheduling
Also: non-overlapping intervals
Interval scheduling sorts by end time and keeps each interval that starts after the last kept one ends.
Template: Greedy

Math & bits 20

位运算bit manipulation
Also: bitwise operations
With bit manipulation I can test the k-th bit using a shift and an AND.
Template: Bits & Math
异或XOR
Also: exclusive or
Since a XOR a is zero, XOR-ing every number leaves the one that appears once.
Template: Bits & Math
位掩码bitmask
Also: mask
I use a bitmask to record which letters a word contains, one bit per letter.
Template: Bits & Math
最低位的 1(lowbit)lowest set bit
Also: x & -x
x AND negative x isolates the lowest set bit, which is how a Fenwick tree jumps.
Template: Bits & Math
左移 / 右移bit shift
Also: left shift · right shift
A left shift by one doubles the number, as long as it doesn't overflow.
Template: Bits & Math
补码two's complement
In two's complement, negative x equals NOT x plus one.
Template: Bits & Math
二进制中 1 的个数popcount
Also: Hamming weight · set bits · bit count
Popcount, the number of set bits, is a single built-in call in most languages.
Template: Bits & Math
快速幂fast exponentiation
Also: binary exponentiation · fast power
Fast exponentiation squares the base every round, so it needs only O(log n) multiplications.
Template: Bits & Math
取模modulo
Also: mod · modular arithmetic
I take the result modulo ten to the ninth plus seven after every addition.
乘法逆元modular inverse
Also: Fermat's little theorem
The modulus is prime, so the modular inverse of a is a to the power of the modulus minus two.
最大公约数greatest common divisor
Also: GCD · Euclidean algorithm
The Euclidean algorithm finds the GCD in a logarithmic number of steps.
最小公倍数least common multiple
Also: LCM
The least common multiple is a divided by the GCD, times b; dividing first avoids overflow.
埃氏筛(素数筛)sieve of Eratosthenes
Also: prime sieve
The sieve of Eratosthenes crosses out the multiples of each prime and finds every prime up to n in O(n log log n).
质因数分解prime factorization
Trial division up to the square root of n gives the prime factorization.
组合数binomial coefficient
Also: n choose k · combinatorics
The binomial coefficient n choose k counts the ways to pick k items out of n.
鸽巢原理(抽屉原理)pigeonhole principle
By the pigeonhole principle, n plus one numbers from one to n must contain a duplicate.
容斥原理inclusion-exclusion
Also: inclusion-exclusion principle
By inclusion-exclusion, the numbers divisible by two or three are the two counts minus the numbers divisible by six.
奇偶性parity
Also: odd and even
Every move changes the sum by an even number, so its parity never changes and an odd target can't be reached from an even start.
向上取整除法ceiling division
Also: round up
For ceiling division with integers, I compute a plus b minus one, divided by b.
蓄水池抽样reservoir sampling
Reservoir sampling keeps the i-th item with probability one over i, so every item is equally likely to be chosen.