1. Home
Data Structure

Data Structure Tutorial: Everything You Need to Know

Learn all about data structures with our comprehensive tutorial. Master the fundamentals and advance your skills in organizing and managing data efficiently.

  • 60
  • 14
right-top-arrow
25

Adjacency Lists in Data Structure: An Overview

Updated on 07/08/2024469 Views

Introduction

An adjacency list is an essential data structure used to construct graphs. Graphs are composed of vertices and edges, the latter showing connections between nodes. In an adjacency list, each vertex in the graph is linked to a list of its neighboring vertices. This structure has gained a lot of popularity among data scientists because it is convenient for storing sparse graphs (graphs with a small number of connections between vertices) and allows traversing the graph.

Definition of Adjacency Lists

Adjacency lists are the data structures used to represent graphs. In the representation, each vertex (or node) of the graph is accompanied by a list of its neighboring vertices. Let V be a vertex; then, the list for V contains all the vertices connected with V, that is, the vertices incident on V by the edge. The list notation is particularly useful for sparse graphs when the number of edges is much lower than the number of possible edges.

Components of an Adjacency List

An adjacency list consists of two main components:

  • Vertices: They are the vertices of the graph and each is illustrated by a unique identifier. In the list, each vertex is linked to a list of its neighboring vertices.
  • Lists of Neighbors: In the graph, any vertex is accompanied by a list comprising all the vertices that are in direct connection with it by an edge. Such lists depict the graph's edges. The lists can be represented by different data structures, such as arrays, linked lists, or hash maps, depending on the programming language and the exact needs of the application.

Example Representation:

Let's consider a simple undirected graph with vertices A, B, C, and D with the subsequent edges:

  • A connects to B directly and to D.
  • B is connected to A and C.
  • C is with B.
  • D is associated with A.

The adjacency list representation for this graph would be:

A: [B, D]

B: [A, C]

C: [B]

D: [A]

In this representation,

  • Vertex A is connected to vertices B and D.
  • Vertex B is attached to vertices A and C.
  • Vertex C is linked to vertex B.
  • Vertex D is also linked to vertex A.

Every line symbolizes a vertex that has neighboring vertices.

Overview of Adjacency List Representation of Graph

Graphs are mathematical structures that are used to represent relationships between objects relating to each other in pairs. They consist of two main components: vertices (also called nodes) and edges. Nodes stand for things, and lines are used to demonstrate ties between them. Charts are predominantly utilized in such areas as computer science, mathematics, biology, and social sciences, mostly thanks to their ability to model very intricate relationships.

Graphs can be either directed or undirected based on whether the edges have a specific direction or not. In directed graphs, the directed edges have the direction, while in undirected graphs the edges do not have the direction. Besides the weighted graphs where each edge has a numerical value or weight that is used as the strength or cost of the connection between the vertices.

Various Ways to Represent Graphs

There are many ways to represent graphs, each with its own advantages and use cases:

  • Adjacency Matrix: It is a 2D array where the rows and columns represent vertices, and the entries show if there is an edge between the corresponding vertices.
  • Adjacency List: An adjacency list undirected graph is a set of lists or arrays in which each list or array is analogous to a vertex, and its elements are the vertices that are connected with it.

The representations have different space as well as time complexities depending on the operations like edge insertion, deletion, and traversal. These factors also determine the suitability of these structures in different scenarios under the specific requirements of the application.

Implementation of Adjacency Lists

For implementing adjacency lists, you can use a data structure that is good at storing and retrieving the neighbors of each vertex efficiently. One of the mentioned algorithms is to apply a hash table (or dictionary in some languages) in which the keys are the vertices and the values are lists that hold the neighbors of each vertex.

Here is a basic outline of the adjacency list in the data structure in Python:

class Graph:

def __init__(self):

self.adj_list = {}

def add_vertex(self, vertex):

if vertex not in self.adj_list:

self.adj_list[vertex] = []

def add_edge(self, src, dest):

if src in self.adj_list and dest in self.adj_list:

self.adj_list[src].append(dest)

# If the graph is undirected, uncomment the line below

# self.adj_list[dest].append(src)

def get_neighbors(self, vertex):

return self.adj_list.get(vertex, [])

def __str__(self):

return str(self.adj_list)

The implementation provides you with an array of services, like adding vertices and edges to the graph and searching for neighbors of a particular vertex.

Applications of Adjacency Lists

The adjacency list in Python is fundamental to graph theory and has numerous applications across various domains.

  1. Graph Algorithms: The lists are the basis of the implementation of various graph algorithms like breadth-first search (BFS), depth-first search (DFS), Dijkstra's shortest path algorithm, Prim's minimum spanning tree algorithm, and Kruskal's minimum spanning tree algorithm. In these algorithms, the nodal neighboring information is accessed remarkably efficiently through the use of these lists.
  1. Network Analysis: The lists are employed in network analysis as a means of displaying the web of connections between entities in networks. This could be analyzing the links between computers in a network, the interactions between proteins in a biological network, or the connections between web pages on the World Wide Web. Like centrality measures, social network analysis techniques will help calculate the role of each individual. Such methods as degree centrality, betweenness centrality, community detection, and network visualization often involve adjacency lists.
  1. Social Network Analysis: It is the study of relationships and interactions between people or groups of people in a social network. Adjacency lists constitute the conventional approach to displaying social networks, where individuals are represented by nodes and relationships (such as friends, followers, and interactions) are edges. These provide means for different data analyses, such as network identification, measuring influence, detecting anomalies, and node prediction.
  1. Recommendation Systems: Adjacency lists are the key elements in recommendation systems, especially in collaborative filtering techniques. In such systems, users and items like movies, products, or articles are represented as a node, while the interactions between users and items are represented as edges. By applying these lists recommendation engines can suggest users items based on their interests, behaviors, and similarities with other users.

The lists are the base data structure in graph theory and they have many applications in graph algorithms, network analysis, social network analysis, and recommendation systems. They allow the use of entities and their relationships and consequently are an essential component of many fields of study.

Real-world Examples

1. Graph Algorithms:

  • Shortest Path Finding: In transportation networks like Google Maps, the adjacency lists are used to find the shortest path between two locations. Intersections (namely, nodes) are joined together with intersections between lines (edges) that contain their respective distances, which is required for efficient pathfinding algorithms.
  • Social Network Algorithms: Facebook's friend suggestion feature consists of adjacency list graph algorithms such as BFS or DFS on the lists, which help uncover mutual connections between users and then recommend potential friends based on those relationships.

2. Network Analysis:

  • Internet Routing: Internet routers utilize adjacency lists to find the most suitable routes for data packets. BGP, the Border Gateway Protocol, utilizes adjacency to establish lists between routers and share routing information.
  • Biological Networks: Biologists tend to employ adjacency matrices to explore protein-protein interaction networks. Every protein is a node, and the interaction is an edge. Through the lists, scientists can determine which proteins are crucial and elucidate biological ways.

3. Social Network Analysis:

  • Twitter: Twitter uses adjacency lists to analyze user input and detect influential users according to their interaction. Twitter can determine the users with a large number of followers or who have a great impact on their networks through the analysis of who follows whom.
  • LinkedIn: LinkedIn's matching suggestions leverage an adjacency list-directed graph to recommend people who have similar connections, interests, and professional circles among others.

4. Recommendation Systems:

  • Amazon: Amazon, using adjacency lists, powers its recommendation engine; it shows products to customers reflecting their browsing history, purchasing behavior, and similarities with other customers. Amazon can come up with personalized recommendations by analyzing the lists of customer-product interactions.
  • Netflix: The recommendation system of Netflix employs an adjacency list that proposes TV shows or movies based on the user’s viewing history, ratings, and similarities with other user watches. Netflix can derive these personalized recommendations by analyzing the connections between its users and movies.

In these cases, adjacency is the fundamental data structure that enables the effective representation and analysis of the relationships between entities in different real-world situations. They are vital for executing tasks such as algorithms running, recommendations being made, and networks and relationships being understood.

Final Words

Adjacency lists are an amazing and useful data structure that can be used in lots of different ways all over the world. By presenting social networks and transportation systems together, the lists are used to represent the relationships between entities and to optimize various algorithms.

The lists are so efficient in storing and traversing graphs that they are already being used for real-world applications, such as Facebook's social graph, Google Maps' routing algorithm, and Netflix's recommendation system. Through the use of these lists, the platforms provide personalized experiences, optimize resource utilization, and, at the same time, improve the satisfaction of users.

FAQs

1. What are the features of the adjacency list?

Adjacency list represents a graph as an array of lists. Each array element represents a vertex of the graph.

2. Why is an adjacency list needed?

Adjacency lists are needed to efficiently represent and work with graphs, especially sparse ones, where there are relatively few edges compared to the total number of possible edges.

3. What is adjacent in data structure?

In the data structure, "adjacent" refers to vertices that are directly connected by an edge.

4. What are adjacencies in a graph?

Adjacencies in a graph refer to the relationships between vertices, indicating which vertices are directly connected by edges.

5. What data type is an adjacency list?

An adjacency list is typically implemented using arrays (or lists) of lists. The outer list represents vertices, and each inner list contains the adjacent vertices.

6. How do you use an adjacency list?

To use an adjacency list, you typically create a list where each element corresponds to a vertex in the graph. Each element holds a list of adjacent vertices. This structure allows efficient access to adjacent vertices and easy traversal of the graph.

7. What is the size of the adjacency list?

The size of an adjacency list is equal to the number of vertices in the graph.

8. What is the space used for the adjacency list?

The space used by an adjacency list depends on the number of vertices and edges in the graph. In general, for a graph with V vertices and E edges, the space complexity of the adjacency list is O(V + E). For sparse graphs, it is often more memory-efficient compared to other representations like adjacency matrices.

Mukesh kumar

Mukesh kumar

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...