AlgoTales · Roadmap

Adjacency list

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

An adjacency list stores a network by giving every item its own small list of neighbours. To see who is connected to something you read just that one list, and items with few links cost almost no space. It is the default way to hold friends, roads or links in memory.

Practical use cases

  • Web app: Friend list on a social profile. On a profile page you tap "Friends" and expect the list instantly. The app keeps, for every user id, a short list of friend ids, so showing one person's friends means reading one list, not searching every friendship in the site. With a million users who each have about 150 friends, memory stays small and the page opens at once.
  • Web app: Related products on a shop page. A shop shows "People also bought" under each product. Each product id holds a list of other product ids that often share a cart. Loading the widget is one lookup in a PHP array or a Redis key, rather than scanning the whole order history, so the product page stays fast on a sale day.
  • Web app: Category tree and menu links. A CMS has pages that link to other pages, and the editor wants to see "which pages link here". Storing for each page the list of pages it points to makes broken-link checks and menus simple. A site with 5,000 pages needs about as many list entries as real links, not a 5,000 by 5,000 grid.
  • System: Web crawlers and map apps. A crawler remembers for each page the pages it links to, and a map app remembers for each junction the roads leaving it. Almost every graph routine, such as search, shortest path and ordering, is written to walk these lists one neighbour at a time.

The story: Raju's Address Notebook

Raju at the chai stall had regular customers, and each knew a few others. He tried Zoya's big grid idea but the grid page filled the whole counter, with almost all boxes empty. His regulars were chatting about 5 people each, not 500.

So Raju took a small notebook and gave each customer one page. On Mira's page he wrote only the names of the people Mira knew. On Aarav's page, only Aarav's people. No empty boxes at all. Pages for lonely customers stayed short.

When someone asked "Who does Mira know?", Raju opened her page and read the list. When a gossip started, he passed the news from page to page. The notebook was small, quick to update, and perfect for "who are the neighbours?" questions.

That notebook is an adjacency list: for every vertex, a list of its neighbours. It is the most common way to store a graph in real programs.

How to spot this problem, and where you need it

You need to store who is connected to whom, and most items have only a few connections compared with the total, so a full table of every possible pair wastes memory and is slow to read.

Signs you need it

  • Your data is naturally "things plus links between them": friends, followers, roads, page links, prerequisites, or parent and child references.
  • You keep asking "who are the neighbours of X?" and your current code loops through a giant list of all links to answer it.
  • You are tempted to build a huge two-dimensional array of true/false for every pair, and most cells are empty.

Where to use it in a project

  • A followers and following feature where each user id maps to an array of ids, kept in memory or in a Redis set.
  • A route planner or dependency checker that must visit the neighbours of one node again and again.

The solution

Make a dictionary (a PHP associative array or a JavaScript object or Map) where each key is an item and each value is a list of the items it connects to. To add a link, push onto the list. For an undirected link such as friendship, push in both lists. To visit neighbours, just loop over one list. Only real links take space, so the structure stays small as the network grows.

Payoff: Before: scanning 5 million friendship rows to show one profile. After: reading one list of about 150 ids, so the page loads in a blink.

Explain it like I am 8

Every child gets a sticky note. On the note, write the names of that child's friends. To know a child's friends, just read their note. Children with few friends have tiny notes, and nobody wastes paper.

How it works, step by step

  1. Make a map from each vertex to an (initially empty) list.
  2. For each edge A-B push B into A's list and, if undirected, push A into B's list.
  3. List the neighbours of a vertex by reading its list. This is what BFS and DFS do all day.
  4. Weighted? Store pairs like (neighbour, weight) in the list instead of just the neighbour.
  5. Check an edge by scanning one short list (or use a set for O(1) lookup).

The code in four languages

PHP

<?php
$edges = [['A','B'], ['A','C'], ['A','D'], ['B','C'], ['D','E']];

// Build: each vertex gets a page (list) of neighbours.
$adj = [];
foreach ($edges as [$a, $b]) {
    $adj[$a][] = $b;       // PHP creates the list automatically
    $adj[$b][] = $a;       // undirected: write on both pages
}
ksort($adj);

foreach ($adj as $v => $list) echo $v . ' -> ' . implode(', ', $list) . "\n";

echo 'Neighbours of A: ' . implode(', ', $adj['A']) . "\n";
echo 'Road C-D? ' . (in_array('D', $adj['C'], true) ? 'yes' : 'no') . "\n";

JavaScript

const edges = [['A','B'], ['A','C'], ['A','D'], ['B','C'], ['D','E']];

// Build: each vertex gets a page (list) of neighbours.
const adj = {};
for (const [a, b] of edges) {
  (adj[a] = adj[a] || []).push(b);   // create the list when first needed
  (adj[b] = adj[b] || []).push(a);   // undirected: write on both pages
}

for (const v of Object.keys(adj).sort()) console.log(v + ' -> ' + adj[v].join(', '));

console.log('Neighbours of A: ' + adj['A'].join(', '));
console.log('Road C-D? ' + (adj['C'].includes('D') ? 'yes' : 'no'));

Java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String[][] edges = {{"A", "B"}, {"A", "C"}, {"A", "D"}, {"B", "C"}, {"D", "E"}};

        // Build: each vertex gets a page (list) of neighbours.
        Map<String, List<String>> adj = new TreeMap<>();
        for (String[] e : edges) {
            adj.computeIfAbsent(e[0], k -> new ArrayList<>()).add(e[1]);   // create the list when first needed
            adj.computeIfAbsent(e[1], k -> new ArrayList<>()).add(e[0]);   // undirected: write on both pages
        }

        for (var entry : adj.entrySet()) {
            System.out.println(entry.getKey() + " -> " + String.join(", ", entry.getValue()));
        }

        System.out.println("Neighbours of A: " + String.join(", ", adj.get("A")));
        System.out.println("Road C-D? " + (adj.get("C").contains("D") ? "yes" : "no"));
    }
}

Go

package main

import (
	"fmt"
	"sort"
	"strings"
)

func main() {
	edges := [][2]string{{"A", "B"}, {"A", "C"}, {"A", "D"}, {"B", "C"}, {"D", "E"}}

	// Build: each vertex gets a page (list) of neighbours.
	adj := map[string][]string{}
	for _, e := range edges {
		adj[e[0]] = append(adj[e[0]], e[1]) // append works on a missing key too
		adj[e[1]] = append(adj[e[1]], e[0]) // undirected: write on both pages
	}

	names := make([]string, 0, len(adj))
	for v := range adj {
		names = append(names, v)
	}
	sort.Strings(names)
	for _, v := range names {
		fmt.Println(v + " -> " + strings.Join(adj[v], ", "))
	}

	fmt.Println("Neighbours of A: " + strings.Join(adj["A"], ", "))
	road := "no"
	for _, x := range adj["C"] {
		if x == "D" {
			road = "yes"
		}
	}
	fmt.Println("Road C-D? " + road)
}

Time: List neighbours O(degree) · edge check O(degree) · Extra space: O(V + E). Memory grows with the actual number of roads, not with the square of the vertices.

Watch out for

  • Writing the neighbour on only one page for an undirected graph.
  • Forgetting vertices that have no edges, so they have no page at all and crash lookups.
  • Using the list for edge checks on very dense graphs. A set per vertex (or a matrix) is faster.

Quick check

  1. Which is the main strength of an adjacency list?
    • Small memory for graphs with few edges
    • Instant yes/no for any pair
    • Sorted output
  2. An adjacency list for 3 undirected edges holds how many neighbour entries in total?
    • 3
    • 6
    • 9
  3. How do you store weights in an adjacency list?
    • You cannot
    • Put weights in a separate sorted array
    • Keep (neighbour, weight) pairs