Commonly Asked Data Structure Interview Questions on Graph

Last Updated : 23 Jul, 2026

Graph interview questions are commonly asked to evaluate your understanding of graph representations, traversals, shortest path algorithms, and graph-based problem solving. This collection covers the most important graph concepts to help you prepare for coding and technical interviews.

  • Covers the most frequently asked graph interview questions with concise explanations.
  • Suitable for both freshers and experienced professionals preparing for technical interviews.

Theoretical Questions for Interviews

1. What is a Graph Data Structure?

A graph is a non-linear data structure that consists of a set of vertices (nodes) connected by edges. It is used to represent relationships or connections between different entities.

  • Consists of vertices (nodes) and edges (connections).
  • Can represent directed or undirected relationships.
  • Widely used in networks, maps, social media, and routing problems.

2. What are the Different Types of Graphs?

Graphs can be classified based on their edge direction, edge weights, connectivity, and structural properties.

1. Based on Edge Direction

2. Based on Edge Weights

3. Based on Connectivity

  • Connected Graph: A path exists between every pair of vertices.
  • Disconnected Graph: One or more vertices are not reachable from others.

4. Based on Cycles

  • Cyclic Graph: Contains at least one cycle.
  • Acyclic Graph: Contains no cycles.

5. Based on Structure

3. What is a Cycle in a Graph?

A cycle is a path in a graph that starts and ends at the same vertex, with no repeated vertices or edges except the starting and ending vertex.

  • Begins and ends at the same vertex.
  • Visits each intermediate vertex only once.
  • Can exist in both directed and undirected graphs.
Detect Cycle in a Directed Graph - GeeksforGeeks

4. What is the Difference Between a Directed and an Undirected Graph?

A directed graph stores edges with a specific direction, whereas an undirected graph stores edges without any direction, allowing traversal in both ways. The following are the major differences between directed and undirected graphs:

FeatureDirected GraphUndirected Graph
Edge DirectionEdges have a directionEdges have no direction
RepresentationOrdered pair (u, v)Unordered pair {u, v}
TraversalAllowed only in the edge directionAllowed in both directions
RelationshipOne-wayTwo-way
ExampleOne-way roads, task dependenciesFriendships, two-way roads
directed_graph

5. What are the Different Ways to Represent a Graph?

A graph can be represented in different ways depending on the operations to be performed and the memory requirements. The choice of representation affects the efficiency of graph algorithms.

1. Adjacency Matrix

  • Represents the graph using a 2D matrix.
  • Stores 1 (or the edge weight) if an edge exists; otherwise stores 0.
  • Suitable for dense graphs.

2. Adjacency List

  • Represents each vertex with a list of its adjacent vertices.
  • Uses less memory for sparse graphs.
  • Most commonly used graph representation.

3. Edge List

  • Stores the graph as a list of edges.
  • Each edge is represented as a pair (or tuple) of vertices.
  • Useful when processing or sorting edges, such as in Kruskal's algorithm.

4. Incidence Matrix

  • Uses a matrix where rows represent vertices and columns represent edges.
  • Each cell indicates whether a vertex is incident to an edge.
  • Commonly used in graph theory and network analysis.

6. What is an Adjacency Matrix?

An adjacency matrix represents a graph using a 2D array, where each cell indicates whether an edge exists between two vertices.

  • Uses a V × V matrix to represent the graph.
  • Stores 1 (or the edge weight) if an edge exists; otherwise stores 0.
  • Supports constant-time O(1) edge lookup.
  • Best suited for dense graphs with many edges.
adjacency_matrix

7. What is an Adjacency List?

An adjacency list is a graph representation in which each vertex maintains a list of all the vertices directly connected to it. Instead of storing every possible edge, it stores only the existing connections, making it memory-efficient.

  • Stores the neighbors of each vertex in separate lists.
  • Requires O(V + E) memory, where V is the number of vertices and E is the number of edges.
  • Efficient for traversing the neighbors of a vertex.
  • Best suited for sparse graphs with fewer edges.
adjacency_list

8. What is the Difference Between an Adjacency Matrix and an Adjacency List?

An adjacency matrix stores graph connections in a 2D array, whereas an adjacency list stores a list of neighboring vertices for each vertex. The following table summarizes the key differences between the two representations:

FeatureAdjacency MatrixAdjacency List
Representation2D arrayArray (or map) of lists
Space ComplexityO(V²)O(V + E)
Edge LookupO(1)O(degree of vertex)
Traversing NeighborsO(V)O(degree of vertex)
Adding an EdgeO(1)O(1) (average)
Removing an EdgeO(1)O(degree of vertex)
Best Suited ForDense graphsSparse graphs

9. What is Depth First Search (DFS)?

Depth First Search (DFS) is a graph traversal algorithm that explores a path as deeply as possible before backtracking to visit other vertices. It is commonly implemented using recursion or a stack.

  • Traverses vertices by moving to the deepest unvisited vertex first.
  • Uses a stack (explicitly or through recursion) for traversal.
  • Commonly used for cycle detection, topological sorting, and connected component analysis.
dfs

10. What is Breadth First Search (BFS)?

Breadth First Search (BFS) is a graph traversal algorithm that visits vertices level by level, exploring all neighboring vertices before moving to the next level. It is commonly implemented using a queue.

  • Visits vertices level by level from the starting vertex.
  • Uses a queue to maintain the traversal order.
  • Useful for shortest paths and level-order traversal.
bfs

11. What is the Difference Between DFS and BFS?

DFS explores a graph by going as deep as possible before backtracking, whereas BFS explores the graph level by level by visiting all neighboring vertices first. The following table summarizes the

key differences between DFS and BFS:

FeatureDFSBFS
Traversal OrderGoes deep before backtrackingVisits vertices level by level
Data Structure UsedStack (or recursion)Queue
Shortest PathDoes not guarantee shortest pathFinds the shortest path in unweighted graphs
Memory UsageUsually lowerUsually higher
Common ApplicationsCycle detection, topological sortingShortest path, level-order traversal
bfs_vs_dfs

12. What is the Time Complexity of DFS and BFS?

The time complexity of both Depth First Search (DFS) and Breadth First Search (BFS) depends on the graph representation. For an adjacency list, both algorithms visit each vertex and edge at most once.

Graph RepresentationDFSBFS
Adjacency ListO(V + E)O(V + E)
Adjacency MatrixO(V²)O(V²)

Where:

  • V = Number of vertices
  • E = Number of edges

Note: Both DFS and BFS have the same time complexity. The difference between them lies in the traversal strategy and the data structure used (stack for DFS and queue for BFS).

13. How do you Find the Shortest Path in an Unweighted Graph?

The shortest path in an unweighted graph is typically found using Breadth First Search (BFS). Since BFS visits vertices level by level, the first time a vertex is reached is guaranteed to be through the shortest path.

Steps:

  1. Start BFS from the source vertex.
  2. Mark each visited vertex and store its parent.
  3. Continue until the destination vertex is reached.
  4. Reconstruct the path by following the parent pointers.
Shortest-Path-in-an-Unweighted-Graph

Input: V = 8, E = 10, S = 0, D = 7, edges[][] = {{0, 1}, {1, 2}, {0, 3}, {3, 4}, {4, 7}, {3, 7}, {6, 7}, {4, 5}, {4, 6}, {5, 6}}
Output: 0 3 7
Explanation: BFS explores the graph level by level. Starting from 0, it first visits its adjacent vertices and continues exploring the next level. Since 7 is first reached through 0 -> 3

-> 7, this is the shortest path containing only 2 edges.

14. How do you Find the Shortest Path in a Weighted Graph?

The shortest path in a weighted graph is found using algorithms that consider the weights assigned to edges. The choice of algorithm depends on whether the graph contains negative edge weights.

15. What is Dijkstra's Algorithm and How Does it Work?

Dijkstra's algorithm is a shortest path algorithm used to find the minimum distance from a source vertex to all other vertices in a weighted graph with non-negative edge weights.

  • Finds the shortest path from a source to all reachable vertices.
  • Works only with non-negative edge weights.
  • Uses a priority queue (min-heap) for efficient processing.

Working of Dijkstra's Algorithm

  1. Initialize the source vertex with distance 0 and all other vertices with ∞.
  2. Select the unvisited vertex with the smallest tentative distance.
  3. Update the distances of all its adjacent vertices if a shorter path is found.
  4. Mark the current vertex as visited.
  5. Repeat until all vertices are processed.
dijkstras

If the source vertex is 0, the shortest path to vertex 4 is:

0 -> 1 -> 4

Total Cost: 4 + 6 = 10

Explanation: Dijkstra's algorithm selects the minimum-cost path by updating the shortest distance to each vertex until all reachable vertices are processed.

16. What is a Spanning Tree?

A spanning tree is a subgraph of a connected graph that includes all the vertices and connects them using the minimum number of edges without forming any cycles.

  • Contains all the vertices of the original graph.
  • Has exactly V − 1 edges, where V is the number of vertices.
  • Does not contain any cycles.
spanningtreedrawio

17. What is a Minimum Spanning Tree (MST)?

A Minimum Spanning Tree (MST) is a spanning tree of a weighted, connected graph that connects all vertices with the minimum possible total edge weight without forming any cycles.

  • Connects all vertices with the minimum total edge weight.
  • Contains exactly V − 1 edges and no cycles.
  • Can be found using Prim's or Kruskal's algorithm.

18. What is Kruskal's Algorithm?

Kruskal's algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a weighted, connected graph. It repeatedly selects the edge with the smallest weight while ensuring that no cycles are formed.

Working of Kruskal's Algorithm

  1. Sort all edges in ascending order of their weights.
  2. Select the smallest edge that does not form a cycle.
  3. Repeat until V - 1 edges are included in the MST.

19. What is Prim's Algorithm?

Prim's algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a weighted, connected graph. It starts from any vertex and repeatedly adds the minimum-weight edge that connects a visited vertex to an unvisited vertex.

Working of Prim's Algorithm

  1. Choose any vertex as the starting point.
  2. Select the minimum-weight edge connected to the visited vertices.
  3. Add the new vertex to the MST.
  4. Repeat until all vertices are included.

20. How do you Detect a Cycle in a Directed Graph?

A cycle in a directed graph can be detected using Depth First Search (DFS) by maintaining an additional recursion stack (or recursion state) along with the visited array. If DFS encounters a vertex that is already present in the recursion stack, a cycle exists.

  • Uses DFS along with a recursion stack.
  • A back edge indicates the presence of a cycle.
  • Runs in O(V + E) time.

Working

  1. Start DFS from an unvisited vertex.
  2. Mark the current vertex as visited and add it to the recursion stack.
  3. Visit all adjacent vertices recursively.
  4. If an adjacent vertex is already in the recursion stack, a cycle is detected.
  5. Remove the current vertex from the recursion stack after all its neighbors are processed.

Coding Interview Questions

The following list of 50 coding problems on Graphs covers a range of difficulty levels, from easy to hard, to help candidates prepare for interviews.

Easy Problems

Medium Problems

Hard Problems

Comment