Code templates
Here are code templates for common patterns for all the data structures and algorithms looked at in LICC.
Two pointers: one input, opposite ends
Two pointers: two inputs, exhaust both
Sliding window
Build a prefix sum
Efficient string building
In JavaScript, benchmarking shows that concatenation with
+=
is faster than using .join().
Linked list: fast and slow pointer
Reversing a linked list
Find number of subarrays that fit an exact criteria
Monotonic increasing stack
The same logic can be applied to maintain a monotonic queue.
Binary tree: DFS (recursive)
Binary tree: DFS (iterative)
Binary tree: BFS
Graph: DFS (recursive)
For the graph templates, assume the nodes are numbered from 0
to n - 1
and the graph is given as an adjacency list. Depending on the problem, you may need to convert the input into an equivalent adjacency list before using the templates.
Graph: DFS (iterative)
Graph: BFS
Find top k elements with heap
Binary search
Binary search: duplicate elements, left-most insertion point
Binary search: duplicate elements, right-most insertion point
Binary search: for greedy problems
If looking for a minimum:
If looking for a maximum:
Backtracking
Dynamic programming: top-down memoization
Build a trie
Dijkstra's algorithm
Comments
Post a Comment