Home Cheat Sheets Data Structures & Algorithms Cheat Sheet
📋 CHEAT SHEET

Data Structures & Algorithms Cheat Sheet

Complete DSA quick reference — time/space complexities, Java implementations, sorting, searching, graph algorithms, dynamic programming, and backtracking patterns.

Arrays & Strings — Time Complexity

OperationArray (Static)ArrayList (Dynamic)Notes
Access by indexO(1)O(1)Direct memory address
Search (unsorted)O(n)O(n)Linear scan
Search (sorted)O(log n)O(log n)Binary search
Insertion at endn/aO(1) amortisedResize doubles capacity
Insertion at indexn/aO(n)Shifts right elements
Deletion at indexn/aO(n)Shifts left elements
Arrays.sort(arr)O(n log n)O(n log n)Dual-pivot quicksort
Collections.sort(list)O(n log n)O(n log n)Timsort (stable)

Arrays & Strings — Java Snippets

TaskJava CodeResult
Declare arrayint[] arr = {1, 2, 3}
Sort arrayArrays.sort(arr)O(n log n)
Sort listCollections.sort(list)O(n log n)
Char digit to intint d = '4' - '0'd = 4
Char to StringString s = String.valueOf('e')"e"
Char to ASCII(int) 'a'97
Char array to Stringnew String(new char[]{'a','e'})"ae"
Increment char(char)('a' + 1)'b'
Is letter or digitCharacter.isLetterOrDigit(c)true/false
Copy listnew ArrayList<>(anotherList)New list with same items
Append to StringBuildersb.append(char or String)
String to char arraystr.toCharArray()char[]
Substringstr.substring(i, j)chars i to j-1
String containsstr.contains("abc")true/false

Linked List — Time Complexity

OperationSingly LinkedDoubly LinkedNotes
Access by indexO(n)O(n)Must traverse from head
SearchO(n)O(n)Linear scan
Insert at headO(1)O(1)Adjust head pointer
Insert at tailO(1)*O(1)*Only if tail pointer kept
Insert at indexO(n)O(n)Traverse then insert
Delete at headO(1)O(1)Adjust head pointer
Delete at indexO(n)O(n)Traverse then delete

HashMap / HashSet — Time Complexity

OperationAverageWorst CaseNotes
get(key)O(1)O(n)Worst = all keys same bucket
put(key, val)O(1)O(n)Hash collision degrades
containsKey(key)O(1)O(n)
remove(key)O(1)O(n)
IterationO(n)O(n)Visits all entries
HashMap order❌ No orderUse LinkedHashMap for insertion order
LinkedHashMap order✅ Insertion orderSlightly slower than HashMap
TreeMap order✅ Sorted by keyO(log n) opsRed-black tree underneath
HashSet duplicates❌ No duplicatesUses HashMap internally

Stack / Queue / Deque / Heap

StructureOrderKey Methods (Java)Use Case
StackLIFOpush(v), pop(), peek()DFS, undo history, balanced brackets
Queue (LinkedList)FIFOoffer(v), poll(), peek()BFS, task scheduling
Deque (LinkedList)Both endsofferFirst/Last, pollFirst/Last, peekFirst/LastSliding window, monotonic deque
PriorityQueueMin-heap defaultoffer(v), poll(), peek()Dijkstra, top-K problems
PriorityQueue (max)Max-heapnew PriorityQueue<>(Comparator.reverseOrder())Top-K largest elements
ArrayDequeBoth ends, fasterpush, pop, offer, pollPrefer over Stack and LinkedList

Sorting Algorithms — Big O Comparison

AlgorithmBestAverageWorstSpaceStable?
Merge SortO(n log n)O(n log n)O(n log n)O(n)✅ Yes
Quick SortO(n log n)O(n log n)O(n²)O(log n)❌ No
Heap SortO(n log n)O(n log n)O(n log n)O(1)❌ No
Tim Sort (Java default)O(n)O(n log n)O(n log n)O(n)✅ Yes
Insertion SortO(n)O(n²)O(n²)O(1)✅ Yes
Selection SortO(n²)O(n²)O(n²)O(1)❌ No
Bubble SortO(n)O(n²)O(n²)O(1)✅ Yes
Counting SortO(n+k)O(n+k)O(n+k)O(k)✅ Yes
Radix SortO(nk)O(nk)O(nk)O(n+k)✅ Yes

Binary Search — Patterns

PatternWhen to UseTemplate Key LineComplexity
Exact matchFind index of target in sorted arrayif arr[mid] == target return midO(log n) time, O(1) space
Left boundaryFirst position ≥ targetif arr[mid] < target: lo = mid+1O(log n) time, O(1) space
Right boundaryLast position ≤ targetif arr[mid] > target: hi = mid-1O(log n) time, O(1) space
Search on answerMin/max satisfying a conditionBinary search on result space, not arrayO(n log n) time
Rotated arrayArray rotated at pivot pointCheck which half is sorted firstO(log n) time
2D matrix searchSorted matrix, find elementTreat as flattened 1D arrayO(log(m×n)) time

Graph Algorithms — Big O

AlgorithmTimeSpaceUse Case
BFSO(V+E)O(V) — queueShortest path (unweighted), level order
DFSO(V+E)O(H) — call stackCycle detection, topological sort, connected components
Dijkstra (min-heap)O((V+E) log V)O(V)Shortest path (non-negative weights)
Bellman-FordO(V·E)O(V)Shortest path (negative weights allowed)
Floyd-WarshallO(V³)O(V²)All-pairs shortest path
Topological Sort (Kahn)O(V+E)O(V)DAG ordering (build deps, course schedule)
Union-FindO(α(n)) ≈ O(1)O(V)Connected components, Kruskal's MST
Prim's MSTO(E log V)O(V)Minimum spanning tree (dense graphs)
Kruskal's MSTO(E log E)O(V)Minimum spanning tree (sparse graphs)
A* SearchO(E log V)O(V)Heuristic shortest path (grid/map)

DFS vs BFS — When to Use

PropertyDFSBFS
Data structureStack (or recursion)Queue
OrderLIFOFIFO
Space complexityO(H) — tree heightO(W) — max width of level
Best when target isDeep in the tree/graphClose to the source
Tree traversalsPreorder, Inorder, PostorderLevel-order
Shortest path❌ Not guaranteed✅ Guaranteed (unweighted)
Cycle detection✅ Easy with visited set✅ Possible
Topological sort✅ Natural fit✅ Kahn's algorithm
Connected components✅ Yes✅ Yes
Memory on wide graphs✅ Better❌ Can explode
Iterative DFS (explicit stack)Avoids StackOverflowError on deep graphsDeque as stack: push right, pop right

Tree Types & Properties

Tree TypeKey PropertyHeightUse Case
Binary TreeEach node ≤ 2 childrenO(n) worstGeneral hierarchical data
Binary Search TreeLeft < Node < RightO(log n) balancedOrdered search/insert/delete
AVL TreeBalance factor ∈ {-1,0,1}O(log n) guaranteedFrequent lookups, balanced BST
Red-Black TreeColour rules ensure balanceO(log n) guaranteedJava TreeMap/TreeSet internals
Heap (Min/Max)Parent ≤/≥ childrenO(log n)Priority Queue, Heap Sort
TrieEach edge = one characterO(L) — word lengthAutocomplete, prefix search
Segment TreeEach node = range aggregateO(log n) updates/queriesRange sum/min/max queries
Fenwick TreeBIT — prefix sumsO(log n) updates/queriesEfficient prefix sum with updates
B-TreeBalanced, multi-key nodesDatabase indexing (MySQL InnoDB)
B+ TreeAll data in leaves, linked leaf listRange queries — faster sequential scan than B-Tree
Suffix TreeCompressed trie of all suffixesString matching: find substring in O(m)

Dynamic Programming — Pattern Recognition

PatternSignal in ProblemFormula ShapeExample Problems
Min/Max path to target"minimum cost/steps to reach"dp[i] = min(dp[i-1], dp[i-2]…) + cost[i]Climbing Stairs, Min Cost Path
Distinct ways (count)"how many ways to reach"dp[i] = dp[i-1] + dp[i-2] + …Coin Change II, Unique Paths
0/1 Knapsack"pick or skip each item"dp[i][w] = max(dp[i-1][w], dp[i-1][w-wt]+val)0/1 Knapsack, Subset Sum
Unbounded Knapsack"use item multiple times"dp[i][w] = max(dp[i-1][w], dp[i][w-wt]+val)Coin Change, Rod Cutting
Longest common substr"two sequences, align chars"if s1[i]==s2[j]: dp[i][j]=dp[i-1][j-1]+1LCS, Edit Distance
Interval DP"merge/split subproblems"dp[i][j] = dp[i][k] + dp[k+1][j] + costMatrix Chain, Burst Balloons
Decision making"buy/sell or take/skip"dp[i][0/1] = max(hold, sell/buy)Best Time to Buy/Sell Stock
Palindrome DP"substring is palindrome"dp[i][j] = dp[i+1][j-1] if s[i]==s[j]Palindrome Partitioning, LPS
State Compression (Bitmask DP)Subset of n items (n ≤ 20)dp[mask] — travelling salesman, assignment problems
Digit DPCount numbers in [L,R] with propertyProcess digit by digit, track tight constraint flag

Backtracking — Core Patterns

PatternKey IdeaPruning ConditionExample Problems
SubsetsAdd current element or skipSkip duplicate nums[i]==nums[i-1]Subsets I & II
PermutationsPick unused elements in any orderSkip if tempList.contains(nums[i])Permutations I & II
CombinationsPick from remaining elements onlyremain < 0 → prune branchCombination Sum I & II
Palindrome partitionCheck if substring is palindrome before addingisPalindrome(s, start, i)Palindrome Partitioning
N-QueensPlace queen if no row/col/diagonal conflictCheck column and diagonalsN-Queens, N-Queens II
Word SearchDFS on grid, mark visited, unmark on backtrackOut of bounds or char mismatchWord Search I & II
Sudoku SolverTry 1-9 for each empty cell, backtrack on conflictRow/col/box already has digitSudoku Solver
Memoize overlapping subproblemsBacktracking + cache = top-down DPIf same (index, state) recurs, cache result → avoid exponential blowup

Bit Manipulation — Quick Reference

OperationExpressionResult / Use Case
Check if even/oddn & 10 = even, 1 = odd
Multiply by 2n << 1n × 2 (left shift)
Divide by 2n >> 1n ÷ 2 (right shift, floor)
Clear last set bitn & (n-1)Removes lowest 1-bit — count set bits
Extract last set bitn & (-n)Isolates lowest 1-bit — Fenwick Tree
XOR same valuesn ^ n0 — find single non-duplicate
XOR with zeron ^ 0n — identity property
Toggle bit in ^ (1 << i)Flips bit at position i
Set bit in | (1 << i)Forces bit i to 1
Clear bit in & ~(1 << i)Forces bit i to 0
Check bit i(n >> i) & 11 if bit i is set, else 0
Is power of 2n > 0 && (n & (n-1)) == 0true if exactly one bit set
Brian Kernighan — count set bitsn & (n-1) clears lowest set bitwhile(n){ count++; n &= n-1; } → O(set bits)
Hamming distanceNumber of differing bits between a and bInteger.bitCount(a ^ b) — XOR then popcount

Two Pointers & Sliding Window

TechniqueWhen to UseTemplate ShapeExamples
Two pointers (opposite ends)Sorted array, find pair with target sumlo=0, hi=n-1, move inwardTwo Sum II, Valid Palindrome
Two pointers (same dir)Remove duplicates, merge sorted arraysslow=0, fast iteratesRemove Duplicates, Move Zeroes
Fixed windowSubarray/substring of size kAdd right, remove left when size>kMax Sum Subarray of Size K
Variable window (expand)Longest subarray satisfying conditionExpand right, shrink left when violatedLongest Substring Without Repeat
Variable window (shrink)Smallest subarray satisfying conditionShrink left while condition holdsMinimum Window Substring
Fast & slow pointersCycle detection in linked list / arrayslow moves 1 step, fast moves 2Linked List Cycle, Find Duplicate
Monotonic StackNext greater / smaller elementMaintain decreasing stack; pop when current > top
Monotonic DequeSliding window maximum/minimumDeque stores indices; evict out-of-window and smaller elements from back

Complexity Quick Reference

Big ONameExample Operationsn=1M approx ops
O(1)ConstantHash lookup, array index, stack push1
O(log n)LogarithmicBinary search, balanced BST ops~20
O(n)LinearLinear scan, single loop1,000,000
O(n log n)LinearithmicMerge sort, heap sort, most good sorts~20,000,000
O(n²)QuadraticBubble/insertion/selection sort, nested loops10¹²
O(2ⁿ)ExponentialSubsets, recursive Fibonacci without memoHuge — avoid
O(n!)FactorialBrute-force permutationsAstronomical — backtrack/prune

Greedy Patterns

PatternKey InsightClassic Problems
Activity SelectionAlways pick earliest finish timeInterval scheduling, meeting rooms
Fractional KnapsackSort by value/weight ratioNot applicable to 0/1 knapsack
Huffman EncodingMerge two smallest frequencies firstOptimal prefix-free codes, file compression
Jump GameTrack max reachable index at each stepLeetCode 55 — greedy beats DP here
Interval MergingSort by start, merge overlappingMerge Intervals (LeetCode 56)
Two-City SchedulingSort by cost difference (A-B)Greedy assignment with constraint

Union-Find (Disjoint Set)

OperationComplexityNotes
find(x) with path compressionO(α(n)) ≈ O(1)Flatten tree on every find call
union(x, y) with rankO(α(n)) ≈ O(1)Attach smaller tree under larger
Connected componentsO(E · α(V))Process all edges, count distinct roots
Cycle detection (undirected)O(E · α(V))Union returns false if same component → cycle
Kruskal's MSTO(E log E + E · α(V))Sort edges by weight, union if different components
Templateparent[i]=i; rank[i]=0find: if parent[i]!=i: parent[i]=find(parent[i]); return parent[i]

Trie (Prefix Tree)

OperationComplexityUse Case
insert(word)O(m) — m = word lengthBuild dictionary, autocomplete index
search(word)O(m)Exact word lookup
startsWith(prefix)O(m)Autocomplete, IP routing
delete(word)O(m)Unmark isEnd; prune empty nodes
Word Search IITrie + DFS on boardPrune branches early — far faster than brute force
StructureTrieNode{ children[26], isEnd }children = new TrieNode[26] or HashMap for Unicode
More Cheat Sheets
Java Collections Cheat SheetJava Streams API Cheat SheetPython Built-in Functions Cheat SheetSQL Joins Cheat SheetDocker Commands Cheat SheetJVM Memory Model DiagramHow HashMap Works InternallyMicroservices Cheat SheetPandas Cheat Sheet