All Computer Algorithms Study Guide
All Computer Algorithms Study Guide
Important note: No single PDF can literally list every algorithm ever invented. This guide covers the main
families and representative algorithms that students, programmers, and technical readers most often need.
Page 1
Computer Algorithms Study Guide
Contents
- 1. What is an algorithm?
- 2. Big-O and complexity basics
- 3. Algorithm design techniques
- 4. Core data structures used by algorithms
- 5. Searching algorithms
- 6. Sorting algorithms
- 7. Recursion and backtracking
- 8. Greedy algorithms
- 9. Dynamic programming
- 10. Graph algorithms
- 11. Tree and heap algorithms
- 12. String and text algorithms
- 13. Mathematical and number algorithms
- 14. Cryptography, hashing, and checksums
- 15. Compression algorithms
- 16. Computational geometry
- 17. Randomized and probabilistic algorithms
- 18. Databases and storage algorithms
- 19. Operating system and distributed algorithms
- 20. Optimization and machine learning algorithms
- 21. Algorithm choice cheat sheets
- 22. Revision checklist and practice prompts
Page 2
Computer Algorithms Study Guide
1. What Is an Algorithm?
An algorithm is a precise step-by-step method for solving a problem. It takes input, follows clear
instructions, and produces output. A good algorithm is correct, understandable, efficient, and suitable for
the constraints of the problem.
Correctness The algorithm gives the right answer for all valid inputs. Binary search only works if the list is sorted.
Efficiency How much time and memory the algorithm needs. Merge sort is usually faster than bubble sort for
large lists.
Trade-off A benefit that comes with a cost. Hash tables are fast but use extra memory.
Key idea: An algorithm is not the same as a programming language. The same algorithm can be written in
Python, JavaScript, C++, Java, or any other language.
O(log n) Logarithmic Very slow growth. Binary search, balanced tree search.
O(n) Linear Double input roughly doubles work. Linear search, scanning a list.
O(n log n) Linearithmic Good for many sorting tasks. Merge sort, heap sort, average quicksort.
Time vs space
- Time complexity asks: how many operations are needed?
- Space complexity asks: how much extra memory is needed?
- Sometimes you use more memory to make the algorithm faster, for example hash tables and dynamic
programming tables.
- Worst case is the slowest possible case. Average case is typical behaviour. Best case is often less
useful for planning.
Page 3
Computer Algorithms Study Guide
Two nested loops over n items O(n^2) For every item, you may compare with every other item.
Repeatedly halving the input O(log n) The problem size shrinks quickly.
Divide, solve two halves, then merge O(n log n) There are log n levels and n work per level.
Try every subset O(2^n) Each item is either included or not included.
Divide and conquer Split problem, solve parts, combine results. Merge sort, quicksort, binary search, closest pair.
Greedy Make the locally best choice now. Activity selection, Huffman coding, Dijkstra, Kruskal,
Prim.
Dynamic programming Store answers to overlapping subproblems. Knapsack, LCS, edit distance, shortest paths in
DAGs.
Backtracking Build a solution, undo when stuck. Sudoku, N-Queens, permutations, combinations.
Branch and bound Search but prune using bounds. Optimisation variants of TSP and integer
programming.
Randomized Use randomness to improve average performance or Randomized quicksort, reservoir sampling, Monte
simplicity. Carlo.
Approximation Find a good enough answer when exact is too slow. Approximation for NP-hard optimisation problems.
Problem-solving workflow
1. Understand the input and output.
2. Estimate constraints: n = 100? 10,000? 10,000,000?
3. Choose a data structure: array, hash table, stack, queue, tree, graph.
4. Choose a design technique: brute force, greedy, DP, backtracking, etc.
5. Prove or test correctness.
6. Analyse time and space complexity.
7. Implement carefully and test edge cases.
Linked list Easy insertion/deletion if node is Insert, delete, traverse. Queues, memory allocators.
known.
Stack Last-in, first-out. push, pop, peek. DFS, undo, parsing brackets.
Deque Insert/remove at both ends. push front/back, pop front/back. Sliding window algorithms.
Hash table Very fast average lookup. insert, search, delete. Dictionaries, sets, caches.
Heap / priority queue Quick access to smallest/largest push, pop min/max. Dijkstra, scheduling, heap sort.
priority.
Tree Hierarchical data and ordered search, insert, traversal. BST, file systems, parse trees.
search.
Graph Networks of relationships. BFS, DFS, shortest path. Maps, social networks, dependencies.
Trie Fast prefix search. insert word, prefix lookup. Autocomplete, dictionaries, IP routing.
Page 4
Computer Algorithms Study Guide
5. Searching Algorithms
Searching means finding an item, position, answer, or condition. It may happen in an array, tree, graph,
database, or search space.
Linear Search
Main idea Used for Typical complexity
Check items one by one until the target is found. Small or unsorted lists. Time: O(n). Space: O(1).
Binary Search
Main idea Used for Typical complexity
Repeatedly compare with the middle and discard Sorted arrays, answer search on monotonic Time: O(log n). Space: O(1) iterative.
half. conditions.
low = 0, high = n - 1
while low <= high:
mid = (low + high) // 2
if A[mid] == target: return mid
if A[mid] < target: low = mid + 1
else: high = mid - 1
return not_found
Tree search Use tree ordering or structure. BST, AVL, red-black tree.
Exponential search Find a range by doubling, then binary search. Sorted unbounded/infinite-like arrays.
Interpolation search Estimate position using value distribution. Uniformly distributed sorted numeric data.
6. Sorting Algorithms
Sorting rearranges data into order. Sorting is important because many other algorithms become faster
after data is sorted.
Selection sort O(n^2) all cases O(1) Usually no Few writes; educational.
Insertion sort O(n) / O(n^2) / O(n^2) O(1) Yes Small or nearly sorted data.
Merge sort O(n log n) all cases O(n) Yes Reliable sorting; linked lists; external sorting.
Quicksort O(n log n) avg, O(n^2) worst O(log n) No Fast in practice with good pivots.
Heap sort O(n log n) all cases O(1) No Good worst-case memory-limited sorting.
Timsort O(n) best, O(n log n) worst O(n) Yes Real-world built-in sort in Python/Java.
Page 5
Computer Algorithms Study Guide
Merge Sort
Main idea Used for Typical complexity
Split the list in half, sort each half, then merge Reliable general-purpose sorting and external Time: O(n log n). Space: O(n).
sorted halves. sorting.
merge_sort(A):
if len(A) <= 1: return A
left = merge_sort(first half)
right = merge_sort(second half)
return merge(left, right)
- Common mistake: Forgetting that the merge step must preserve order and takes linear time.
Quicksort
Main idea Used for Typical complexity
Pick a pivot, partition smaller values left and Fast in-memory sorting with good pivot selection. Average: O(n log n). Worst: O(n^2).
larger values right, then recurse.
Recursion pattern
recursive_function(problem):
if problem is small enough:
return direct answer # base case
split or reduce the problem
call recursive_function on smaller problem(s)
combine the results
Backtracking pattern
backtrack(state):
if state is a complete solution:
save or return it
for each possible choice:
if choice is valid:
make choice
backtrack(new state)
undo choice
Sudoku solver Fill empty cells, backtrack on invalid placements. Exponential worst case
DFS maze solving Explore a path, backtrack when blocked. O(V+E) for graph form
8. Greedy Algorithms
A greedy algorithm makes the best-looking local choice at each step. Greedy is fast and elegant, but it
only works when local choices can be proven to lead to a global optimum.
Page 6
Computer Algorithms Study Guide
Fractional knapsack Take highest value/weight ratio first. Items can be split. O(n log n).
Huffman coding Merge two lowest-frequency symbols Prefix-code compression. O(n log n).
repeatedly.
Dijkstra Choose unvisited node with smallest known Shortest paths with non-negative weights. O((V+E) log V) with
distance. heap.
Kruskal Add smallest edge that does not create a Minimum spanning tree. O(E log E).
cycle.
Prim Grow tree using smallest outgoing edge. Minimum spanning tree. O(E log V) with heap.
Warning: Greedy does not solve 0/1 knapsack correctly in general, because items cannot be split. That
problem usually needs dynamic programming or search.
Activity Selection
Main idea Used for Typical complexity
Sort by finish time and repeatedly choose the Scheduling the maximum number of compatible Time: O(n log n) due to sorting.
activity that ends earliest without overlapping. tasks.
- Common mistake: Sorting by start time or duration looks reasonable but can fail.
9. Dynamic Programming
Dynamic programming (DP) solves problems with overlapping subproblems and optimal substructure.
Instead of recalculating the same thing many times, DP stores answers in a table or memo cache.
Two styles of DP
Style How it works When it feels natural
Top-down memoization Write recursive solution and cache answers. When the recurrence is easy to express
recursively.
Bottom-up tabulation Fill a table from smaller cases to larger cases. When the order of computation is clear.
Common DP algorithms/problems
Problem State idea Typical complexity Use
Fibonacci DP dp[i] = dp[i-1] + dp[i-2] O(n) Intro to memoization.
0/1 Knapsack best value using first i items and capacity w O(nW) Selection under capacity.
Longest Common Subsequence best subsequence length for prefixes O(nm) Text comparison, DNA.
Edit Distance min operations to convert prefix A to prefix B O(nm) Spell check, similarity.
Longest Increasing Subsequence best increasing subsequence ending at i O(n^2) or O(n log n) Sequence analysis.
Matrix Chain Multiplication best split point for multiplying matrices O(n^3) Optimization of
computation order.
Floyd-Warshall shortest path using first k intermediate nodes O(V^3) All-pairs shortest paths.
0/1 Knapsack DP
Main idea Used for Typical complexity
For each item, choose either take it or leave it, Choosing items under a fixed weight/budget Time: O(nW). Space: O(nW) or O(W).
then keep best value for each capacity. limit.
Page 7
Computer Algorithms Study Guide
- Common mistake: Updating a one-dimensional DP array in the wrong direction can reuse an item more than once.
How to recognise DP
- The problem asks for best, minimum, maximum, count, or number of ways.
- A brute-force recursive solution repeats the same subproblems.
- A decision at one step depends on results from smaller cases.
- You can define a state, recurrence, base case, and answer location.
Shortest path with negative Bellman-Ford O(VE) Can detect negative cycles.
edges
Minimum spanning tree Kruskal, Prim O(E log V) Connects all vertices cheaply.
Maximum flow Ford-Fulkerson, Edmonds-Karp, Varies Capacity and network flow problems.
Dinic
BFS(start):
queue = [start]
visited = {start}
while queue not empty:
v = queue.pop_front()
Page 8
Computer Algorithms Study Guide
DFS(v):
mark v as visited
for each neighbor u of v:
if u not visited:
DFS(u)
- Common mistake: Forgetting visited nodes can cause infinite loops in cyclic graphs.
Dijkstra's Algorithm
Main idea Used for Typical complexity
Repeatedly finalise the unvisited node with the Shortest paths with non-negative edge weights. Time: O((V+E) log V) using a priority queue.
smallest known distance.
dist[start] = 0
priority_queue.push((0, start))
while queue not empty:
d, v = pop smallest distance
if d is outdated: continue
for each edge v -> u with weight w:
if dist[v] + w < dist[u]:
dist[u] = dist[v] + w
push(dist[u], u)
Graph representations
Representation Memory Good for Weakness
Adjacency list O(V+E) Sparse graphs, BFS/DFS/Dijkstra. Checking if a specific edge exists
may take time.
Adjacency matrix O(V^2) Dense graphs, fast edge check. Wastes memory on sparse graphs.
Binary search tree Left values < node < right values. Search/insert/delete O(h), where h is
height.
Red-black tree Self-balancing BST with colour rules. O(log n), used in many libraries.
Heap Parent priority is before child priority. push/pop O(log n), peek O(1).
Segment tree Tree storing range summaries. Range query/update O(log n).
Fenwick tree Compact structure for prefix sums. Prefix query/update O(log n).
Page 9
Computer Algorithms Study Guide
Heap Operations
Main idea Used for Typical complexity
Maintain a partially ordered tree so the min or Priority queues, heap sort, Dijkstra, scheduling. push/pop: O(log n). peek: O(1).
max priority is easy to access.
heap_push(x):
add x at end
bubble x upward while parent has lower priority
heap_pop():
replace root with last item
bubble root downward until heap property is restored
- Common mistake: A heap is not a fully sorted structure; only the root is guaranteed to be min/max.
find(x):
if parent[x] != x:
parent[x] = find(parent[x]) # path compression
return parent[x]
union(a, b):
rootA = find(a); rootB = find(b)
attach smaller tree under larger tree
KMP Precompute pattern prefix table to avoid O(n+m) Exact pattern search.
rechecking.
Rabin-Karp Use rolling hash to compare quickly. Average O(n+m) Multiple pattern search, plagiarism
detection.
Boyer-Moore Compare from right and skip positions. Often sublinear in Fast text search.
practice
Aho-Corasick Trie plus failure links. O(text + matches) Many patterns at once.
Suffix array Sorted list of suffixes. Search O(m log n) Indexing large texts.
Suffix tree Compressed trie of suffixes. Search O(m) Advanced text indexing.
Knuth-Morris-Pratt (KMP)
Main idea Used for Typical complexity
Use a prefix table so mismatches do not restart Exact substring search in linear time. Time: O(n+m). Space: O(m).
the search from zero.
Page 10
Computer Algorithms Study Guide
- Common mistake: The prefix table stores border lengths, not random jumps.
Extended Euclidean algorithm Find x,y such that ax + by = gcd(a,b). Used for modular inverse.
Modular exponentiation Compute a^b mod m without huge numbers. O(log b).
Newton's method Approximate roots or optimisation points. Fast when conditions are good.
Euclidean Algorithm
Main idea Used for Typical complexity
Repeatedly replace the larger number by the Finding GCD, simplifying fractions, cryptography Time: O(log min(a,b)).
remainder until the remainder is zero. foundations.
gcd(a, b):
while b != 0:
a, b = b, a mod b
return a
- Common mistake: Using subtraction version is correct but much slower for large numbers.
Digital signatures RSA signatures, ECDSA, EdDSA Prove message origin and integrity.
Message authentication HMAC, Poly1305 Verify message authenticity with shared secret.
Security note: Never invent your own encryption algorithm for real security. Use standard, reviewed libraries
and protocols.
Page 11
Computer Algorithms Study Guide
Huffman coding Lossless Short codes for frequent symbols. ZIP components, images,
teaching.
LZ77 / LZ78 Lossless Refer back to repeated previous text. ZIP, PNG, gzip-related
methods.
LZW Lossless Build dictionary of repeated sequences. GIF, old compression formats.
Arithmetic coding Lossless Encode message as interval using probabilities. Advanced compression.
JPEG-style DCT Lossy Transform image blocks and discard high-frequency JPEG images.
details.
MP3/AAC-style Lossy Remove audio details humans hear less. Audio compression.
Choosing compression
- Use lossless compression for code, documents, database backups, and exact records.
- Use lossy compression for media when smaller size matters more than perfect reconstruction.
- Compression works best when data has repetition or predictable patterns.
Closest pair of points Divide and conquer Split points and check crossing strip. O(n log n).
Line segment intersection Orientation tests, sweep line Detect crossings efficiently. O((n+k) log n).
Point in polygon Ray casting, winding number Count crossings or angle winding. O(n).
Voronoi diagram Fortune's algorithm Partition plane by nearest site. O(n log n).
Delaunay triangulation Various algorithms Triangulation related to Voronoi. O(n log n).
Important detail
Geometry algorithms often fail due to floating-point precision errors. Robust implementations use careful
orientation tests, tolerances, or exact arithmetic where necessary.
Page 12
Computer Algorithms Study Guide
Monte Carlo simulation Use random trials to estimate results. Risk, physics, optimisation, probability.
Las Vegas algorithm Random time, always correct answer. Randomized quicksort is often described
this way.
Bloom filter Probabilistic set membership with false positives. Caches, databases, web crawlers.
Skip list Random levels create balanced search structure. Alternative to balanced trees.
False positive example: A Bloom filter may say an item is possibly present when it is not, but it should not say
an inserted item is absent.
Joins Nested-loop join, hash join, sort-merge join Combine rows from tables.
External sorting External merge sort Sort data larger than memory.
CPU scheduling Shortest Job First Minimises average waiting if job lengths known.
CPU scheduling Round Robin Fair time slices for interactive systems.
CPU scheduling Priority scheduling Important tasks first, but may starve low priority tasks.
Big data MapReduce Parallel map and reduce operations across clusters.
Distributed systems warning: Network failures, message delays, and clock differences make distributed
algorithms much harder than single-machine algorithms.
Page 13
Computer Algorithms Study Guide
Optimization algorithms
Algorithm Main idea Used for
Gradient descent Move parameters in direction that reduces loss. Training ML models, numerical
optimisation.
Stochastic gradient descent Use small batches for faster noisy updates. Large-scale ML.
Newton's method Use curvature information for fast convergence. Root finding and optimisation.
Simulated annealing Sometimes accept worse moves to escape local optima. Hard optimisation problems.
Genetic algorithms Evolve candidate solutions using selection/mutation/crossover. Search spaces with weak structure.
Linear programming / simplex Optimise linear objective under linear constraints. Operations research, allocation.
For beginners: Do not try to memorise all ML algorithms first. Learn the difference between supervised
learning, unsupervised learning, classification, regression, clustering, training, validation, overfitting, and loss
functions.
By problem clue
Problem clue Usually consider Why
Data is sorted Binary search, two pointers Sorted order gives structure.
Need items by priority Heap / priority queue Fast min/max priority access.
Need try choices with constraints Backtracking Search tree with pruning.
Need connect all nodes cheaply Minimum spanning tree Kruskal or Prim.
Need pattern in text KMP, Rabin-Karp, Boyer-Moore Avoid repeated matching work.
Need range sum/min/max updates Segment tree / Fenwick tree Efficient range queries.
Page 14
Computer Algorithms Study Guide
By input size
Input size n Usually acceptable Usually risky
n <= 20 O(2^n), backtracking with pruning O(n!) unless heavily pruned.
n >= 1,000,000 O(n), O(n log n) with care High constants or memory-heavy methods.
Sorting choice
Situation Recommended
General-purpose sorting Use the language built-in sort, often highly optimised.
Need O(1) extra memory and good worst case Heap sort.
Practice prompts
- Given a list of 1,000,000 numbers, which sorting algorithms are reasonable and why?
- Why does binary search require sorted data? Trace it on [2, 4, 7, 9, 13, 18].
- A map has roads with distances. Which algorithm finds shortest routes if all distances are
non-negative?
- A graph has edges with negative weights. Which shortest-path algorithm is safer than Dijkstra?
- You need autocomplete for a dictionary. Which data structure helps and why?
- You need to count ways to make change using coins. Why might dynamic programming help?
- You need to detect if two accounts are in the same group after many merge operations. Which
structure helps?
- You need to find a substring in a huge document. Why is naive search sometimes inefficient?
- You need to store passwords. Why is a fast general hash not enough?
Page 15
Computer Algorithms Study Guide
- You need to schedule fair CPU time between many programs. Which OS scheduling ideas apply?
Page 16
Computer Algorithms Study Guide
Sorting Bubble, selection, insertion, shell, merge, quick, heap, counting, radix, bucket, Timsort, external merge sort.
Arrays / sequences Two pointers, sliding window, prefix sums, difference arrays, Kadane's algorithm, monotonic stack/queue.
Recursion / search space Backtracking, branch and bound, DFS search tree, permutations, subsets, N-Queens, Sudoku solver.
Greedy Activity selection, interval scheduling, fractional knapsack, Huffman, Dijkstra, Kruskal, Prim.
Dynamic programming Fibonacci, knapsack, coin change, LCS, LIS, edit distance, matrix chain, DP on trees, bitmask DP.
Graphs BFS, DFS, topological sort, Dijkstra, Bellman-Ford, Floyd-Warshall, A*, Kruskal, Prim, Kosaraju, Tarjan,
Ford-Fulkerson, Edmonds-Karp, Dinic.
Trees Tree traversals, BST operations, AVL rotations, red-black balancing, heap operations, trie operations, segment
tree, Fenwick tree, LCA.
Strings Naive matching, KMP, Rabin-Karp, Boyer-Moore, Aho-Corasick, suffix array, suffix tree, Z-algorithm, edit
distance, regex automata.
Math / number theory Euclid, extended Euclid, sieve, fast exponentiation, modular inverse, CRT, Miller-Rabin, FFT, Gaussian
elimination.
Cryptography AES, ChaCha20, RSA, ECC, Diffie-Hellman, ECDH, ECDSA, EdDSA, SHA-256, SHA-3, HMAC, Argon2.
Compression RLE, Huffman, arithmetic coding, LZ77, LZ78, LZW, DEFLATE, JPEG-style DCT, audio/video codecs.
Geometry Orientation test, convex hull, closest pair, sweep line, point-in-polygon, Voronoi, Delaunay, polygon triangulation.
Randomized Randomized quicksort, reservoir sampling, Bloom filter, skip list, Monte Carlo, Las Vegas algorithms.
Databases B-tree, B+ tree, hash join, sort-merge join, nested-loop join, query optimization, WAL, LRU/LFU cache
replacement.
Operating systems FCFS, SJF, round robin, priority scheduling, LRU/FIFO page replacement, Banker's algorithm, deadlock detection.
Distributed systems Consensus concepts, Paxos, Raft, consistent hashing, vector clocks, leader election, MapReduce.
Machine learning Linear/logistic regression, k-NN, Naive Bayes, decision trees, random forests, boosting, k-means, PCA, SVM,
neural networks, backpropagation, attention.
Optimisation Gradient descent, SGD, Newton, simplex, simulated annealing, genetic algorithms, local search, hill climbing.
Final advice: Algorithms are best learned by tracing small examples by hand, then implementing them, then
testing edge cases. Memorising names alone is not enough.
Page 17