On this page I plan on documenting all the code snippets I use frequently. I’ll use T for generic types, K for generic keys, and V for generic values when necessary. All of this code is written in Java since I think it’s the most user-friendly.

Maps

Frequency Map

Map Iteration

Trees

In-Order Traversal

Pre-Order Traversal

Post-Order Traversal

Level-Order Traversal

Graphs

Depth-First Search

This can be done iteratively with a stack instead of recursively.

Breadth-First Search

Level-Order Traversal

Level-order traversals differ from BFS because they keep track of what “step” of the BFS we’re currently on. This can be handy for problems where we want to know the length of the shortest path, like Word Ladder or Rotting Oranges.

Matrices

Note that matrices are a subset of graphs.

Number of Islands

This is one of my favorite paradigms since it applies to so many different problems.