Edge List
About
An Edge List is a simple way to represent a graph using a list of edges, where:
Each edge is stored as a pair (or triplet for weighted graphs) representing the two connected vertices.
It is best for sparse graphs because it stores only edges and not all possible connections.
Why Use an Edge List?
Space Efficient for Sparse Graphs: Only stores the edges, making it O(E) space complexity.
Simple Representation: Easier to implement and manipulate compared to adjacency matrices.
Best for Edge-Centric Operations: Useful when iterating over edges rather than neighbours.
Structure of an Edge List
An Edge List consists of a list of edges, where each edge is stored as a pair (u, v) for an unweighted graph or triplet (u, v, w) for a weighted graph.
Example Graph Representation
Consider a graph with 4 vertices (V = 4) and 4 edges (0→1, 0→2, 1→3, 2→3):
Edges
Start Vertex
End Vertex
Weight (if weighted)
(0, 1)
0
1
-
(0, 2)
0
2
-
(1, 3)
1
3
-
(2, 3)
2
3
-
For a weighted version of the graph with edge weights:
Edges
Start Vertex
End Vertex
Weight
(0, 1, 10)
0
1
10
(0, 2, 20)
0
2
20
(1, 3, 30)
1
3
30
(2, 3, 40)
2
3
40
Implementation using an Edge List
Code
Output
Time Complexity Analysis
Adding an Edge
O(1)
Removing an Edge
O(E)
Checking if an Edge Exists
O(E)
Getting Neighbours
O(E)
Iterating All Edges
O(E)
Space Complexity
O(E)
Weighted Graph Implementation
If the graph is weighted, we store (src, dest, weight) instead of just (src, dest).
Code
Output
Time Complexity Analysis
Operation
Time Complexity
Explanation
addEdge(int src, int dest, int weight)
O(1)
Adding an edge to an ArrayList is a constant-time operation (appending to the list).
removeEdge(int src, int dest)
O(E)
The removeIf() method checks each edge, so it may iterate over all edges in the list.
hasEdge(int src, int dest)
O(E)
It iterates over all edges to check if a specific edge exists.
getEdgeWeight(int src, int dest)
O(E)
Similar to hasEdge(), it checks each edge to find the weight of a matching edge.
getNeighbours(int vertex)
O(E)
Checks all edges to find neighbours of the given vertex.
printGraph()
O(E)
Iterates through all edges to print them, making it linear in the number of edges.
Last updated