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.

Read Full Tutorial β†’

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 orderβ€”Use LinkedHashMap for insertion order
LinkedHashMap orderβœ… Insertion orderβ€”Slightly slower than HashMap
TreeMap orderβœ… Sorted by keyO(log n) opsRed-black tree underneath
HashSet duplicates❌ No duplicatesβ€”Uses 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

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

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

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

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

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

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
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 Architecture DiagramPandas Cheat Sheet