One page

Algorithms and Data Structures cheat sheet

What to keep at hand. If a line is not clear, go back to the matching lesson in the course.

Open the course: Algorithms and Data Structures

Cost of operations

WhatHow
Array: index accessarr[i] // O(1)
Array: push and poparr.push(x); arr.pop() // O(1)
Array: shift and unshiftarr.shift() // O(n)
Array: search by valuearr.includes(x) // O(n)
Sortingarr.sort((a, b) => a - b) // O(n log n)
Map and Set: get, set, hasmap.has(k) // O(1) on average
Binary searchO(log n), sorted data only

Patterns and when to use them

WhatHow
Search inside a loopMap or Set: O(n²) -> O(n)
Pair in a sorted arraytwo pointers toward each other
Contiguous subarray or substringsliding window
Brackets, undo, nestingstack
Shortest path without weightsBFS on a queue
Search in sorted data or over the answerbinary search

Recursion, sorting, trees

WhatHow
Recursionbase case + step toward a smaller problem
Memoizationif (memo.has(n)) return memo.get(n)
Merge sortO(n log n) always, O(n) memory, stable
Quick sortO(n log n) on average, O(n²) in the worst case
Sorting numbersarr.toSorted((a, b) => a - b)
Tree height1 + Math.max(height(node.left), height(node.right))
Inorder in a BSTvalues in ascending order
BST searchO(h): O(log n) balanced, O(n) chain

JavaScript templates

WhatHow
Frequenciescounts.set(x, (counts.get(x) ?? 0) + 1)
Two sumif (seen.has(t - x)) return [seen.get(t - x), i]; seen.set(x, i)
Fixed size windowsum += nums[i] - nums[i - k]
Middle of the rangeconst mid = Math.floor((left + right) / 2)
Top of the stackstack.at(-1)

Other cheat sheets