VOOZH about

URL: https://www.geeksforgeeks.org/dsa/add-and-remove-edge-in-adjacency-list-representation-of-a-graph/

⇱ Add and Remove Edge in Adjacency List representation of a Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Add and Remove Edge in Adjacency List representation of a Graph

Last Updated : 12 Jul, 2025

Prerequisites: Graph and Its Representation
In this article, adding and removing edge is discussed in a given adjacency list representation. 
A vector has been used to implement the graph using adjacency list representation. It is used to store the adjacency lists of all the vertices. The vertex number is used as the index in this vector. 
Example: 
 

Below is a graph and its adjacency list representation: 
 

👁 Image
👁 Image


If the edge between 1 and 4 has to be removed, then the above graph and the adjacency list transforms to: 
 

👁 Image
👁 Image


 


 


Approach: The idea is to represent the graph as an array of vectors such that every vector represents adjacency list of the vertex. 
 

  • Adding an edge: Adding an edge is done by inserting both of the vertices connected by that edge in each others list. For example, if an edge between (u, v) has to be added, then u is stored in v's vector list and v is stored in u's vector list. (push_back)
  • Deleting an edge: To delete edge between (u, v), u's adjacency list is traversed until v is found and it is removed from it. The same operation is performed for v.(erase)


Below is the implementation of the approach: 
 


Output: 
vertex 0 -> 1-> 4
vertex 1 -> 0-> 2-> 3-> 4
vertex 2 -> 1-> 3
vertex 3 -> 1-> 2-> 4
vertex 4 -> 0-> 1-> 3

vertex 0 -> 1-> 4
vertex 1 -> 0-> 2-> 3
vertex 2 -> 1-> 3
vertex 3 -> 1-> 2-> 4
vertex 4 -> 0-> 3

 

Time Complexity: Removing an edge from adjacent list requires, on the average time complexity will be O(|E| / |V|) , which may result in cubical complexity for dense graphs to remove all edges.

Auxiliary Space: O(V) , here V is number of vertices.

Comment
Article Tags:
Article Tags: