Graph Adjacency List

One common graph storage format is called an adjacency list.

In this format, every node has an array of connected neighbors: an adjacency list. We could store these arrays in a hash map where the keys represent the node and the values are the adjacency lists.

For instance, here's one graph:

An example graph composed of 4 labeled vertices.

And, here's how we'd represent it using a hash map:

Map<Integer, Integer[]> graph = new HashMap<Integer, Integer[]>() {{ put(0, new Integer[] {1}); put(1, new Integer[] {0, 2, 3}); put(2, new Integer[] {1, 3}); put(3, new Integer[] {1, 2}); }};

Since node 3 has edges to nodes 1 and 2, graph.get(3) has the adjacency list {1, 2}.

What's next?

If you're ready to start applying these concepts to some problems, check out our mock coding interview questions.

They mimic a real interview by offering hints when you're stuck or you're missing an optimization.

Try some questions now

. . .