DSA Cheat Sheets
Review data structures, time and space complexity, algorithm patterns and Python, Java and C++ code templates.
Big O and operation counts
Count inner work before simplifying the expression. These examples count all unordered index pairs.
Prefix tables and hashing
A leading zero lets one subtraction recover any half-open range sum. C++ uses the vector header for this snippet.
Sorting comparison
Worst-case time and typical auxiliary memory for array implementations. The code inserts each item into its sorted prefix.
String scans
These palindrome examples compare literal ASCII characters. Normalize first only when the task defines a normalization rule.
Two-pointer invariants
On a sorted sequence, the smallest remaining item cannot participate when even its largest partner makes the sum too small.
Sliding window templates
For these maximum-sum examples require 1 ≤ k ≤ length. Initialize the best from a complete window to handle all-negative values.
Binary search boundaries
Find the first value at least x. The return value may equal n, indicating the insertion point after the final value.
Linked list operations
Reversal assumes a finite singly linked chain whose nodes have a next field. Return the new head.
Stack and queue operations
Library examples place two values into a FIFO queue and remove the older value.
Recursive frames
Each descent owns its arguments. Each return supplies the missing operand in its caller. For the fixed-width snippets use 0 ≤ n ≤ 20.
Tree traversal order
These preorder snippets use a binary Node with value, left and right fields. Visit the root before its two subtrees.
Heap indices and order
In a zero-indexed max heap the parent value is at least each child value. Equal keys are permitted.
Graph algorithms
Reachability examples use adjacency lists indexed 0 through V−1 and a valid starting vertex s. Mark before enqueuing.
Dynamic programming states
Count ways of climbing n stairs with jumps of one or two. One empty route reaches stair zero. For signed 64-bit answers use 0 ≤ n ≤ 91.
Greedy interval selection
Count the maximum compatible half-open talks [start, finish), with positive duration and endpoints representable as 32-bit integers.
Bit manipulation formulas
For nonnegative 32-bit inputs, clear the lowest set bit once per loop iteration.
Lower bound template
Find the first value at least the target in sorted input.
Union-find root lookup
Find a representative using path halving.