Algorithms & Data Structures Cheat Sheet

Time Complexity

NotationMeaningExampleCommon Algorithms
O(1)Constant timeAccessing array elementArray access, hash table lookup
O(log n)Logarithmic timeBinary searchBinary search, balanced tree operations
O(n)Linear timeLinear searchLinear search, traversing array
O(n log n)LinearithmicEfficient sortingMerge sort, quick sort average case
O(n²)Quadratic timeBubble sortBubble sort, selection sort
O(2ⁿ)Exponential timeTower of HanoiRecursive algorithms without memoization
O(n!)Factorial timeTraveling salesmanPermutations, brute force

Sorting Algorithms

AlgorithmTime Complexity (Avg)Time Complexity (Worst)Space ComplexityStableBest Use Case
Bubble SortO(n²)O(n²)O(1)YesSmall datasets, educational purposes
Selection SortO(n²)O(n²)O(1)NoSmall datasets, minimal memory writes
Insertion SortO(n²)O(n²)O(1)YesSmall datasets, nearly sorted data
Merge SortO(n log n)O(n log n)O(n)YesStable sort, guaranteed performance
Quick SortO(n log n)O(n²)O(log n)NoGeneral purpose, in-place sorting
Heap SortO(n log n)O(n log n)O(1)NoGuaranteed O(n log n), in-place
Counting SortO(n + k)O(n + k)O(k)YesSmall integer keys, limited range
Radix SortO(d(n + k))O(d(n + k))O(n + k)YesFixed-length keys, integers or strings

Searching Algorithms

AlgorithmTime ComplexitySpace ComplexityRequirementsBest Use Case
Linear SearchO(n)O(1)Unsorted arraySmall arrays, unsorted data
Binary SearchO(log n)O(1)Sorted arrayLarge sorted arrays
Jump SearchO(√n)O(1)Sorted arrayBlock-based searching
Interpolation SearchO(log log n)O(1)Sorted array, uniformly distributedUniformly distributed sorted data
Exponential SearchO(log n)O(1)Sorted arrayUnbounded or infinite arrays

Graph Algorithms

AlgorithmPurposeTime ComplexitySpace ComplexityBest Use Case
BFSShortest path in unweighted graphO(V + E)O(V)Shortest path, level-order traversal
DFSTraverse graph, detect cyclesO(V + E)O(V)Topological sort, cycle detection
DijkstraShortest path in weighted graphO((V + E) log V)O(V)Non-negative weights, single source
Bellman-FordShortest path with negative weightsO(VE)O(V)Negative weights, detect negative cycles
Floyd-WarshallAll-pairs shortest pathsO(V³)O(V²)Small graphs, all-pairs paths
KruskalMinimum Spanning TreeO(E log E)O(E)Sparse graphs, disjoint sets
PrimMinimum Spanning TreeO(E log V)O(V)Dense graphs, priority queue
Topological SortOrder for dependenciesO(V + E)O(V)Task scheduling, dependencies

Data Structures

StructureAccessSearchInsertionDeletionSpaceBest Use Case
ArrayO(1)O(n)O(n)O(n)O(n)Random access, fixed size
StackO(n)O(n)O(1)O(1)O(n)LIFO operations, function calls
QueueO(n)O(n)O(1)O(1)O(n)FIFO operations, BFS
Singly Linked ListO(n)O(n)O(1)O(1)O(n)Dynamic size, frequent insertions/deletions
Doubly Linked ListO(n)O(n)O(1)O(1)O(n)Bi-directional traversal
Hash TableN/AO(1)O(1)O(1)O(n)Fast lookups, key-value pairs
Binary Search TreeO(log n)O(log n)O(log n)O(log n)O(n)Sorted data, range queries
AVL TreeO(log n)O(log n)O(log n)O(log n)O(n)Balanced tree, guaranteed performance
HeapO(1)O(n)O(log n)O(log n)O(n)Priority queue, heap sort

Dynamic Programming Patterns

PatternProblem TypeApproachExample Problems
Grid DP2D path finding2D table, fill row by rowUnique paths, min path sum
KnapsackOptimization with constraintsMaximize value within capacity0/1 knapsack, unbounded knapsack
LISLongest increasing subsequenceCompare with previous elementsLongest increasing subsequence
PalindromesPalindrome problemsExpand around centers or DP tableLongest palindromic substring
PartitionDivide into groupsTry all possible partitionsPartition to equal sum subsets
Bit ManipulationSubset problemsUse bits to represent subsetsGenerate all subsets

String Algorithms

AlgorithmPurposeTime ComplexitySpace ComplexityBest Use Case
KMPPattern matchingO(n + m)O(m)Pattern matching with preprocessing
Rabin-KarpPattern matchingO(n + m)O(1)Multiple pattern search
Z AlgorithmPattern matchingO(n)O(n)Find all occurrences efficiently
TriePrefix operationsO(m)O(ALPHABET_SIZE * N * M)Autocomplete, spell checker
ManacherLongest palindromic substringO(n)O(n)Linear palindrome detection

Common Algorithm Techniques

TechniqueDescriptionWhen to UseExample Problems
GreedyMake locally optimal choicesOptimal substructure, greedy choice propertyActivity selection, Huffman coding
Divide & ConquerBreak into subproblemsProblems that can be dividedMerge sort, binary search
Dynamic ProgrammingStore results of subproblemsOverlapping subproblemsFibonacci, knapsack
BacktrackingTry all possibilitiesConstraint satisfaction problemsN-Queens, Sudoku
Two PointersTwo pointers in data structureSorted arrays, linked listsTwo sum, palindrome check
Sliding WindowFixed/variable size windowSubarray/string problemsMax sum subarray, anagram
BFSLevel-by-level explorationShortest path, tree problemsLevel order traversal, shortest path
DFSDeep explorationGraph/tree traversalConnected components, cycle detection

Tree Traversals

TraversalOrderImplementationUse Case
PreorderRoot → Left → RightProcess root firstCopy tree, expression evaluation
InorderLeft → Root → RightProcess root between subtreesBinary search tree (sorted order)
PostorderLeft → Right → RootProcess root lastDelete tree, expression evaluation
Level OrderLevel by levelUse queueBFS, print tree level by level

Important Algorithms

AlgorithmPurposeTime ComplexitySpace Complexity
Binary SearchFind element in sorted arrayO(log n)O(1)
Fast PowerCompute a^n efficientlyO(log n)O(1)
Euclidean AlgorithmFind GCDO(log min(a,b))O(1)
Extended EuclideanFind GCD and coefficientsO(log min(a,b))O(1)
Sieve of EratosthenesFind all primes up to nO(n log log n)O(n)
Union-FindDisjoint set operationsO(α(n)) amortizedO(n)
Topological SortOrder vertices with dependenciesO(V + E)O(V)
Kadane's AlgorithmMaximum subarray sumO(n)O(1)