Edge list
Beginner · 6 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
An edge list is the simplest way to write down a network: just a flat list of links, each one saying "from A to B" and maybe a cost. It looks exactly like a CSV file or a database table, which is why it is how graphs usually arrive and leave.
Practical use cases
- Web app: Importing a CSV of roads or routes. An admin uploads a CSV with columns from_city, to_city and distance for a delivery app. Each row is one edge, so reading the file line by line already gives you the whole graph. No reshaping is needed before you sort it by distance or count the links.
- Web app: A friendships table in MySQL. A social site stores friendships as rows of user_id and friend_id. That table is an edge list. A report that counts total links, finds the heaviest connection or exports data to another system is one simple query, with no extra structures built.
- Web app: REST API returning links. An API endpoint (a URL that returns data) for a network diagram sends JSON like [{from:1,to:2},{from:2,to:3}]. The front-end chart library takes this list directly and draws the lines, so the back end only has to dump rows. Because the list is flat, the same response can also be cached and reused by every visitor who opens that page.
- System: Kruskal and Bellman-Ford. Some algorithms, such as Kruskal for the cheapest cabling plan and Bellman-Ford for shortest paths with negative costs, simply loop over every link. For them an edge list is the perfect input, and sorting it by cost takes one call.
The story: The Road Contractor's Slip
The district hired a contractor to build roads between villages. He did not want drawings, grids or fancy notebooks. He just asked for a pile of slips, each slip saying: "Village A to village B, cost 4 lakh." One slip per road.
Mira loved how simple this was. Adding a new road meant adding one slip. Nobody had to open pages or fill tables. And when the contractor said, "Show me the cheapest roads first", she just sorted the slips by cost, and the job was done.
But Kabir found a weakness. "If I want to know every road that touches village C, I must read all the slips." True. A pile of slips is great for sorting and processing every road, but slow for "who are the neighbours of C?"
That pile of slips is an edge list: just a list of (from, to, weight). It is the favourite store of algorithms that look at all the edges, like Kruskal and Bellman-Ford.
How to spot this problem, and where you need it
Your network data arrives as a plain list of pairs from a file, form or database table, and you need to decide how to hold it before doing anything clever with it.
Signs you need it
- The input is described as "N lines, each with two ids and a weight", or you see columns like source, target and cost in a table.
- Your algorithm needs to go through all links in some order, for example sort by price, rather than ask about one node at a time.
- You only need to store, count, filter or export links, not walk from node to node.
Where to use it in a project
- Import and export screens for CSV or Excel files that describe connections, such as routes, referrals or dependencies.
- A database table such as follows(user_id, follows_id) that you read with plain SQL.
The solution
Keep an array of small records, each holding from, to and optionally weight. Add a link by appending one record. If an algorithm wants to loop over every link, or sort links by weight, work directly on this array. If you later need fast "who are the neighbours of X?", convert the list once into an adjacency list by looping through it and grouping by the from field.
Payoff: Before: hand-building complex structures just to read a CSV. After: one array holds the whole network, and a single sort call orders every link by cost.
Explain it like I am 8
Imagine a stack of cards. Every card has two village names and a price written on it. That stack is your whole map! Shuffle it, sort it, count it. But to find roads of one village, you flip through all the cards.
How it works, step by step
- Start with an empty list.
- For each road append a triple
[from, to, weight](drop the weight if the graph is unweighted). - For an undirected graph one entry is enough: algorithms simply treat it as going both ways.
- Sort by weight, or loop over every edge when an algorithm needs them all.
- Finding a vertex's neighbours means scanning the entire list.
The code in four languages
PHP
<?php
// Edge list: [from, to, cost]
$edges = [
['A','B',4], ['A','C',2], ['B','C',5],
['B','D',10], ['C','D',3], ['D','E',7],
];
// Neighbours of C: scan EVERY edge.
$nb = [];
foreach ($edges as [$a, $b, $w]) {
if ($a === 'C') $nb[] = $b . '(' . $w . ')';
elseif ($b === 'C') $nb[] = $a . '(' . $w . ')';
}
echo 'Roads at C: ' . implode(', ', $nb) . "\n";
// Sorting by cost is easy with an edge list.
usort($edges, fn($p, $q) => $p[2] <=> $q[2]);
foreach ($edges as [$a, $b, $w]) echo "$a-$b cost $w\n";JavaScript
// Edge list: [from, to, cost]
const edges = [
['A','B',4], ['A','C',2], ['B','C',5],
['B','D',10], ['C','D',3], ['D','E',7],
];
// Neighbours of C: scan EVERY edge.
const nb = [];
for (const [a, b, w] of edges) {
if (a === 'C') nb.push(b + '(' + w + ')');
else if (b === 'C') nb.push(a + '(' + w + ')');
}
console.log('Roads at C: ' + nb.join(', '));
// Sorting by cost is easy with an edge list.
const sorted = [...edges].sort((p, q) => p[2] - q[2]);
for (const [a, b, w] of sorted) console.log(a + '-' + b + ' cost ' + w);Java
import java.util.*;
public class Main {
record Edge(String a, String b, int cost) {}
public static void main(String[] args) {
// Edge list: from, to, cost
List<Edge> edges = new ArrayList<>(List.of(
new Edge("A", "B", 4), new Edge("A", "C", 2), new Edge("B", "C", 5),
new Edge("B", "D", 10), new Edge("C", "D", 3), new Edge("D", "E", 7)));
// Neighbours of C: scan EVERY edge.
List<String> nb = new ArrayList<>();
for (Edge e : edges) {
if (e.a().equals("C")) nb.add(e.b() + "(" + e.cost() + ")");
else if (e.b().equals("C")) nb.add(e.a() + "(" + e.cost() + ")");
}
System.out.println("Roads at C: " + String.join(", ", nb));
// Sorting by cost is easy with an edge list.
edges.sort(Comparator.comparingInt(Edge::cost));
for (Edge e : edges) System.out.println(e.a() + "-" + e.b() + " cost " + e.cost());
}
}Go
package main
import (
"fmt"
"sort"
"strings"
)
type Edge struct {
a, b string
cost int
}
func main() {
// Edge list: from, to, cost
edges := []Edge{
{"A", "B", 4}, {"A", "C", 2}, {"B", "C", 5},
{"B", "D", 10}, {"C", "D", 3}, {"D", "E", 7},
}
// Neighbours of C: scan EVERY edge.
var nb []string
for _, e := range edges {
if e.a == "C" {
nb = append(nb, fmt.Sprintf("%s(%d)", e.b, e.cost))
} else if e.b == "C" {
nb = append(nb, fmt.Sprintf("%s(%d)", e.a, e.cost))
}
}
fmt.Println("Roads at C: " + strings.Join(nb, ", "))
// Sorting by cost is easy with an edge list.
sort.Slice(edges, func(i, j int) bool { return edges[i].cost < edges[j].cost })
for _, e := range edges {
fmt.Printf("%s-%s cost %d\n", e.a, e.b, e.cost)
}
}Time: Add edge O(1) · neighbours of one vertex O(E) · sort O(E log E) · Extra space: O(E). The tiniest storage of all, but every neighbour question reads the whole list.
Watch out for
- Using an edge list for BFS or DFS, which keep asking for neighbours. Convert to an adjacency list first.
- Forgetting that isolated vertices (no edges) do not appear anywhere in an edge list.
- Treating A-B and B-A as two different edges when the graph is undirected.
Quick check
- What is easy with an edge list?
- Instant neighbour lookup
- Sorting all roads by cost
- Checking a pair in O(1)
- To find all neighbours of one vertex in an edge list you must…
- Read one cell
- Sort first
- Scan the whole list
- Which algorithm is naturally written with an edge list?
- Kruskal's minimum spanning tree
- BFS
- Binary search