{"id":22814352,"url":"https://github.com/devinterview-io/graph-data-structure-interview-questions","last_synced_at":"2026-01-11T02:46:39.133Z","repository":{"id":108757739,"uuid":"332398287","full_name":"Devinterview-io/graph-data-structure-interview-questions","owner":"Devinterview-io","description":"🟣 Graph Data Structure interview questions and answers to help you prepare for your next data structures and algorithms interview in 2024.","archived":false,"fork":false,"pushed_at":"2024-01-06T19:28:31.000Z","size":26,"stargazers_count":10,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-30T22:16:32.412Z","etag":null,"topics":["algorithms","algorithms-and-data-structures","algorithms-and-data-structures-interview-questions","algorithms-interview-questions","coding-interview-questions","data-structures","data-structures-and-algorithms","data-structures-and-algorithms-interview-questions","data-structures-interview-questions","graph-data-structure","graph-data-structure-interview-questions","graph-data-structure-questions","graph-data-structure-tech-interview","software-architecture-interview","software-architecture-interview-questions","software-developer-interview","software-engineer-interview"],"latest_commit_sha":null,"homepage":"https://devinterview.io/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Devinterview-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-24T08:14:14.000Z","updated_at":"2025-03-07T09:58:42.000Z","dependencies_parsed_at":"2024-01-06T20:47:49.188Z","dependency_job_id":null,"html_url":"https://github.com/Devinterview-io/graph-data-structure-interview-questions","commit_stats":null,"previous_names":["devinterview-io/graph-data-structure-interview-questions","devinterview-io/graph-theory-interview-questions"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fgraph-data-structure-interview-questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fgraph-data-structure-interview-questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fgraph-data-structure-interview-questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Devinterview-io%2Fgraph-data-structure-interview-questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Devinterview-io","download_url":"https://codeload.github.com/Devinterview-io/graph-data-structure-interview-questions/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246385415,"owners_count":20768672,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithms","algorithms-and-data-structures","algorithms-and-data-structures-interview-questions","algorithms-interview-questions","coding-interview-questions","data-structures","data-structures-and-algorithms","data-structures-and-algorithms-interview-questions","data-structures-interview-questions","graph-data-structure","graph-data-structure-interview-questions","graph-data-structure-questions","graph-data-structure-tech-interview","software-architecture-interview","software-architecture-interview-questions","software-developer-interview","software-engineer-interview"],"created_at":"2024-12-12T13:08:21.353Z","updated_at":"2026-01-11T02:46:39.115Z","avatar_url":"https://github.com/Devinterview-io.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# 50 Essential Graph Data Structure Interview Questions in 2026\n\n\u003cdiv\u003e\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://devinterview.io/questions/data-structures-and-algorithms/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fdata-structures-and-algorithms-github-img.jpg?alt=media\u0026token=fa19cf0c-ed41-4954-ae0d-d4533b071bc6\" alt=\"data-structures-and-algorithms\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n#### You can also find all 50 answers here 👉 [Devinterview.io - Graph Data Structure](https://devinterview.io/questions/data-structures-and-algorithms/graph-data-structure-interview-questions)\n\n\u003cbr\u003e\n\n## 1. What is a _Graph_?\n\nA **graph** is a data structure that represents a collection of interconnected **nodes** through a set of **edges**.\n\nThis abstract structure is highly versatile and finds applications in various domains, from social network analysis to computer networking.\n\n### Core Components\n\nA graph consists of two main components:\n\n1. **Nodes**: Also called **vertices**, these are the fundamental units that hold data.\n2. **Edges**: These are the connections between nodes, and they can be either **directed** or **undirected**.\n\n### Visual Representation\n\n![Graph: Unidirected, Directed, Cyclic, Acyclic, Weighted, Unweighted, Sparse, Dense](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fwhat-is-graph.png?alt=media\u0026token=0d7b76b3-23d6-4a72-99d8-1b84565274b4)\n\n### Graph Representations\n\nThere are several ways to represent graphs in computer memory, with the most common ones being **adjacency matrix**, **adjacency list**, and **edge list**.\n\n#### Adjacency Matrix\n\nIn an adjacency matrix, a 2D Boolean array indicates the edges between nodes. A value of `True` at index `[i][j]` means that an edge exists between nodes `i` and `j`.\n\nHere is the Python code:\n\n```python\ngraph = [\n    [False, True, True],\n    [True, False, True],\n    [True, True, False]\n]\n```\n\n#### Adjacency List\n\nAn adjacency list represents each node as a list, and the indices of the list are the nodes. Each node's list contains the nodes that it is directly connected to.\n\nHere is the Python code:\n\n```python\ngraph = {\n    0: [1, 2],\n    1: [0, 2],\n    2: [0, 1]\n}\n```\n\n#### Edge List\n\nAn edge list is a simple list of tuples, where each tuple represents an edge between two nodes.\n\nHere is the Python code:\n\n```python\ngraph = [(0, 1), (0, 2), (1, 2)]\n```\n\u003cbr\u003e\n\n## 2. What are some common _Types_ and _Categories_ of _Graphs_?\n\nGraphs serve as **adaptable data structures** for various computational tasks and real-world applications. Let's look at their diverse types.\n\n### Types of Graphs\n\n1. **Undirected**: Edges lack direction, allowing free traversal between connected nodes. Mathematically, $(u,v)$ as an edge implies $(v,u)$ as well.\n2. **Directed (Digraph)**: Edges have a set direction, restricting traversal accordingly. An edge $(u,v)$ doesn't guarantee $(v,u)$.\n\n![Graph Types: Unidirected, Directed](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fdirection.png?alt=media\u0026token=187d88ba-04f3-4993-bbcf-f3bc35c41c0d)\n\n#### Weight Considerations\n\n1. **Weighted**: Each edge has a numerical \"weight\" or \"cost.\"\n2. **Unweighted**: All edges are equal in weight, typically considered as 1.\n\n![Graph Types: Weighted, Unweighted](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fweight.png?alt=media\u0026token=c975e0b9-4c21-4518-8c7e-9489279b642b)\n\n#### Presence of Cycles\n\n1. **Cyclic**: Contains at least one cycle or closed path.\n2. **Acyclic**: Lacks cycles entirely.\n\n![Graph Types: Cyclic, Acyclic](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fcyclic.png?alt=media\u0026token=f072557c-d298-4c73-b5b8-11ca014eeb08)\n\n#### Edge Density\n\n1. **Dense**: High edge-to-vertex ratio, nearing the maximum possible connections.\n2. **Sparse**: Low edge-to-vertex ratio, closer to the minimum.\n\n![Graph Types: Sparse, Dense](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fdensity.png?alt=media\u0026token=084eec75-b348-4429-ae30-788ac7f49778)\n\n#### Connectivity\n\n1. **Connected**: Every vertex is reachable from any other vertex.\n2. **Disconnected**: Some vertices are unreachable from others.\n\n![Graph Types: Connected, Disconnected](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fconnected-disconnected-graph.png?alt=media\u0026token=3aa6db3e-852e-4c62-a42d-a6ebf501d9f7)\n\n#### Edge Uniqueness\n\n1. **Multigraph**: Allows duplicate edges between vertices.\n2. **Simple**: Limits vertices to a single connecting edge.\n\n![Graph Types: Multigraph, Simple Graph](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fsimple-multigraph.png?alt=media\u0026token=a7c888e1-a317-470c-94b8-bf998880bdd7)\n\u003cbr\u003e\n\n## 3. What is the difference between a _Tree_ and a _Graph_?\n\n**Graphs** and **trees** are both nonlinear data structures, but there are fundamental distinctions between them.\n\n### Key Distinctions\n\n- **Uniqueness**: Trees have a single root, while graphs may not have such a concept.\n- **Topology**: Trees are **hierarchical**, while graphs can exhibit various structures.\n-  **Focus**: Graphs center on relationships between individual nodes, whereas trees emphasize the relationship between nodes and a common root.\n\n### Graphs: Versatile and Unstructured\n\n- **Elements**: Composed of vertices/nodes (denoted as V) and edges (E) representing relationships. Multiple edges and **loops** are possible.\n- **Directionality**: Edges can be directed or undirected.\n- **Connectivity**: May be **disconnected**, with sets of vertices that aren't reachable from others.\n- **Loops**: Can contain cycles.\n\n### Trees: Hierarchical and Organized\n\n- **Elements**: Consist of nodes with parent-child relationships.\n- **Directionality**: Edges are strictly parent-to-child.\n- **Connectivity**: Every node is accessible from the unique root node.\n- **Loops**: Cycles are not allowed.\n\n### Visual Representation\n\n![Graph vs Tree](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Ftree-graph.jpg?alt=media\u0026token=0362c5d3-e851-4cd2-bbb4-c632e77ccede\u0026_gl=1*euedhq*_ga*OTYzMjY5NTkwLjE2ODg4NDM4Njg.*_ga_CW55HF8NVT*MTY5NzI4NzY1Ny4xNTUuMS4xNjk3Mjg5NjU2LjYwLjAuMA..)\n\u003cbr\u003e\n\n## 4. How can you determine the _Minimum number of edges_ for a graph to remain connected?\n\nTo ensure a graph remains **connected**, it must have a minimum number of edges determined by the number of vertices. This is known as the **edge connectivity** of the graph.\n\n### Edge Connectivity Formula\n\nThe minimum number of edges required for a graph to remain connected is given by:\n\n$$\n\\text{{Edge Connectivity}} = \\max(\\delta(G),1)\n$$\n\nWhere:\n- $\\delta(G)$ is the minimum degree of a vertex in $G$.\n- The maximum function ensures that the graph remains connected even if all vertices have a degree of 1 or 0.\n\nFor example, a graph with a minimum vertex degree of 3 or more requires at least 3 edges to stay connected.\n\u003cbr\u003e\n\n## 5. Define _Euler Path_ and _Euler Circuit_ in the context of graph theory.\n\nIn **graph theory**, an **Euler Path** and an **Euler Circuit** serve as methods to visit all edges (links) exactly once, with the distinction that an Euler Circuit also visits all vertices once.\n\n### Euler Path and Euler Circuit Definitions\n\nA graph has an **Euler Path** if it contains exactly two vertices of odd degree.\n\nA graph has an **Euler Circuit** if every vertex has even degree.\n\n**Degree** specifies the number of edges adjacent to a vertex.\n\n### Key Concepts\n\n- **Starting Vertex**: In an Euler Path, the unique starting and ending vertices are the two with odd degrees.\n- **Reachability**: In both Euler Path and Circuit, every edge must be reachable from the starting vertex.\n- **Direction-Consistency**: While an Euler Path is directionally open-ended, an Euler Circuit is directionally closed.\n\n### Visual Representation: Euler Path and Circuit\n\n![Euler Path and Euler Circuit](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/data%20structures%2Feulerian-path-and-circuit-.webp?alt=media\u0026token=6b2ced12-db4a-435a-9943-ece237d9ef8c)\n\u003cbr\u003e\n\n## 6. Compare _Adjacency Lists_ and _Adjacency Matrices_ for graph representation.\n\nGraphs can be represented in various ways, but **Adjacency Matrix** and **Adjacency List** are the most commonly used data structures. Each method offers distinct advantages and trade-offs, which we'll explore below.\n\n![Example Graph](https://static.javatpoint.com/tutorial/graph-theory/images/graph-representations1.png)\n\n### Space Complexity\n\n- **Adjacency Matrix**: Requires a $N \\times N$ matrix, resulting in $O(N^2)$ space complexity.\n- **Adjacency List**: Utilizes a list or array for each node's neighbors, leading to $O(N + E)$ space complexity, where $E$ is the number of edges.\n\n### Time Complexity for Edge Look-Up\n\n- **Adjacency Matrix**: Constant time, $O(1)$, as the presence of an edge is directly accessible.\n- **Adjacency List**: Up to $O(k)$, where $k$ is the degree of the vertex, as the list of neighbors may need to be traversed.\n\n### Time Complexity for Traversal\n\n- **Adjacency Matrix**: Requires $O(N^2)$ time to iterate through all potential edges.\n- **Adjacency List**: Takes $O(N + E)$ time, often faster for sparse graphs.\n\n### Time Complexity for Edge Manipulation\n\n- **Adjacency Matrix**: $O(1)$ for both addition and removal, as it involves updating a single cell.\n- **Adjacency List**: $O(k)$ for addition or removal, where $k$ is the degree of the vertex involved.\n\n### Time Complexity for Vertex Manipulation\n\n- **Adjacency Matrix**: $O(N^2)$ as resizing the matrix is needed.\n- **Adjacency List**: $O(1)$ as it involves updating a list or array.\n\n### Code Example: Adjacency Matrix \u0026 Adjacency List\n\nHere is the Python code:\n\n```python\nadj_matrix = [\n    [0, 1, 1, 0, 0, 0],\n    [1, 0, 0, 1, 0, 0],\n    [1, 0, 0, 0, 0, 1],\n    [0, 1, 0, 0, 1, 1],\n    [0, 0, 0, 1, 0, 0],\n    [0, 0, 1, 1, 0, 0]\n]\n\nadj_list = [\n    [1, 2],\n    [0, 3],\n    [0, 5],\n    [1, 4, 5],\n    [3],\n    [2, 3]\n]\n```\n\u003cbr\u003e\n\n## 7. What is an _Incidence Matrix_, and when would you use it?\n\nAn **incidence matrix** is a binary graph representation that maps vertices to edges. It's especially useful  for **directed** and **multigraphs**. The matrix contains $0$s and $1$s, with positions corresponding to \"vertex connected to edge\" relationships.\n\n### Matrix Structure\n\n- **Columns**: Represent edges\n- **Rows**: Represent vertices\n- **Cells**: Indicate whether a vertex is connected to an edge\n\nEach unique **row-edge pair** depicts an incidence of a vertex in an edge, relating to the graph's structure differently based on the graph type.\n\n### Example: Incidence Matrix for a Directed Graph\n\n![Directed Graph](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fdirected-graph1.png?alt=media\u0026token=aa5733dc-b79a-4a5f-8f4d-127e1c7b5130)\n\n### Example: Incidence Matrix for an Undirected Multigraph\n\n![Uniderected Graph](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fundirected-graph1.png?alt=media\u0026token=224b6d3a-a2ab-432d-8691-a83483b88cc8)\n\n### Applications of Incidence Matrices\n\n- **Algorithm Efficiency**: Certain matrix operations can be faster than graph traversals.\n- **Graph Comparisons**: It enables direct graph-to-matrix or matrix-to-matrix comparisons.\n- **Database Storage**: A way to represent graphs in databases amongst others.\n- **Graph Transformations**: Useful in transformations like line graphs and dual graphs.\n\u003cbr\u003e\n\n## 8. Discuss _Edge List_ as a graph representation and its use cases.\n\n**Edge list** is a straightforward way to represent graphs. It's apt for dense graphs and offers a quick way to query edge information.\n\n### Key Concepts\n\n- **Edge Storage**: The list contains tuples (a, b) to denote an edge between nodes $a$ and $b$.\n- **Edge Direction**: The edges can be directed or undirected.\n- **Edge Duplicates**: Multiple occurrences signal multigraph. Absence ensures simple graph.\n\n### Visual Example\n\n![Edge List Example](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fedge-list.png?alt=media\u0026token=d1bbe33f-c145-4c40-aff3-a6c4f1e80554)\n\n### Code Example: Edge List\n\nHere is the Python 3 code:\n\n```python\n# Example graph\nedges = {('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D'), ('B', 'D'), ('D', 'E')}\n\n# Check existence\nprint(('A', 'B') in edges)  # True\nprint(('B', 'A') in edges)  # False\nprint(('A', 'E') in edges)  # False\n\n# Adding an edge\nedges.add(('E', 'C'))\n\n# Removing an edge\nedges.remove(('D', 'E'))\n\nprint(edges)  # Updated set: {('A', 'C'), ('B', 'D'), ('C', 'D'), ('A', 'B'), ('E', 'C'), ('B', 'C')}\n```\n\u003cbr\u003e\n\n## 9. Explain how to save space while storing a graph using _Compressed Sparse Row_ (CSR).\n\nIn **Compressed Sparse Row** format, the graph is represented by three linked arrays. This streamlined approach can significantly reduce memory use and is especially beneficial for **sparse graphs**.\n\nLet's go through the data structures and the detailed process.\n\n### Data Structures\n\n1. **Indptr Array (IA)**: A list of indices where each row starts in the `adj_indices` array. It's of length `n_vertices + 1`.\n2. **Adjacency Index Array (AA)**: The column indices for each edge based on their position in the `indptr` array.\n3. **Edge Data**: The actual edge data. This array's length matches the number of non-zero elements.\n\n\n### Visual Representation\n\n![CSR Graph Representation](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fcompressed-sparse-row1.png?alt=media\u0026token=aa1b2449-f800-4962-a7f3-f94431272191)\n\n### Code Example: CSR Graph Representation\n\nHere is the Python code:\n\n```python\nindptr = [0, 2, 3, 5, 6, 7, 8]\nindices = [2, 4, 0, 1, 3, 4, 2, 3]\ndata = [1, 2, 3, 4, 5, 6, 7, 8]\n\n# Reading from the CSR Format\nfor i in range(len(indptr) - 1):\n    start = indptr[i]\n    end = indptr[i + 1]\n    print(f\"Vertex {i} is connected to vertices {indices[start:end]} with data {data[start:end]}\")\n\n# Writing a CSR Represented Graph\n# Vertices 0 to 5, Inclusive.\n# 0 -\u003e [2, 3, 4] - Data [3, 5, 7]\n# 1 -\u003e [0] - Data [1]\n# 2 -\u003e [] - No outgoing edges.\n# 3 -\u003e [1] - Data [2]\n# 4 -\u003e [3] - Data [4]\n# 5 -\u003e [2] - Data [6]\n\n# Code to populate:\n# indptr =  [0, 3, 4, 4, 5, 6, 7]\n# indices = [2, 3, 4, 0, 1, 3, 2]\n# data = [3, 5, 7, 1, 2, 4, 6]\n```\n\u003cbr\u003e\n\n## 10. Explain the _Breadth-First Search_ (BFS) traversing method.\n\n**Breadth-First Search** (BFS) is a graph traversal technique that systematically explores a graph level by level. It uses a **queue** to keep track of nodes to visit next and a list to record visited nodes, avoiding redundancy.\n\n### Key Components\n\n- **Queue**: Maintains nodes in line for exploration.\n- **Visited List**: Records nodes that have already been explored.\n\n### Algorithm Steps\n\n1. **Initialize**: Choose a starting node, mark it as visited, and enqueue it.\n2. **Explore**: Keep iterating as long as the queue is not empty. In each iteration, dequeue a node, visit it, and enqueue its unexplored neighbors.\n3. **Terminate**: Stop when the queue is empty.\n\n### Visual Representation\n\n![BFS Example](https://techdifferences.com/wp-content/uploads/2017/10/BFS-correction.jpg)\n\n### Complexity Analysis\n\n- **Time Complexity**: $O(V + E)$ where $V$ is the number of vertices in the graph and $E$ is the number of edges. This is because each vertex and each edge will be explored only once.\n  \n- **Space Complexity**: $O(V)$ since, in the worst case, all of the vertices can be inside the queue.\n\n### Code Example: Breadth-First Search\n\nHere is the Python code:\n\n```python\nfrom collections import deque\n\ndef bfs(graph, start):\n    visited = set()\n    queue = deque([start])\n    \n    while queue:\n        vertex = queue.popleft()\n        if vertex not in visited:\n            print(vertex, end=' ')\n            visited.add(vertex)\n            queue.extend(neighbor for neighbor in graph[vertex] if neighbor not in visited)\n\n# Sample graph representation using adjacency sets\ngraph = {\n    'A': {'B', 'D', 'G'},\n    'B': {'A', 'E', 'F'},\n    'C': {'F'},\n    'D': {'A', 'F'},\n    'E': {'B'},\n    'F': {'B', 'C', 'D'},\n    'G': {'A'}\n}\n\n# Execute BFS starting from 'A'\nbfs(graph, 'A')\n# Expected Output: 'A B D G E F C'\n```\n\u003cbr\u003e\n\n## 11. Explain the _Depth-First Search_ (DFS) algorithm.\n\n**Depth-First Search** (DFS) is a graph traversal algorithm that's simpler and **often faster** than its breadth-first counterpart (BFS). While it **might not explore all vertices**, DFS is still fundamental to numerous graph algorithms.\n\n### Algorithm Steps\n\n1. **Initialize**: Select a starting vertex, mark it as visited, and put it on a stack.\n2. **Loop**: Until the stack is empty, do the following:\n   - Remove the top vertex from the stack.\n   - Explore its unvisited neighbors and add them to the stack.\n3. **Finish**: When the stack is empty, the algorithm ends, and all reachable vertices are visited.\n\n### Visual Representation\n\n![DFS Example](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2Fdepth-first-search.jpg?alt=media\u0026token=37b6d8c3-e5e1-4de8-abba-d19e36afc570)\n\n### Code Example: Depth-First Search\n\nHere is the Python code:\n\n```python\ndef dfs(graph, start):\n    visited = set()\n    stack = [start]\n    \n    while stack:\n        vertex = stack.pop()\n        if vertex not in visited:\n            visited.add(vertex)\n            stack.extend(neighbor for neighbor in graph[vertex] if neighbor not in visited)\n    \n    return visited\n\n# Example graph\ngraph = {\n    'A': {'B', 'G'},\n    'B': {'A', 'E', 'F'},\n    'G': {'A'},\n    'E': {'B', 'G'},\n    'F': {'B', 'C', 'D'},\n    'C': {'F'},\n    'D': {'F'}\n}\n\nprint(dfs(graph, 'A'))  # Output: {'A', 'B', 'C', 'D', 'E', 'F', 'G'}\n```\n\u003cbr\u003e\n\n## 12. What are the key differences between _BFS_ and _DFS_?\n\n**BFS** and **DFS** are both essential graph traversal algorithms with distinct characteristics in strategy, memory requirements, and use-cases.\n\n### Core Differences\n\n1. **Search Strategy**: BFS moves level-by-level, while DFS goes deep into each branch before backtracking.\n2. **Data Structures**: BFS uses a Queue, whereas DFS uses a Stack or recursion.\n3. **Space Complexity**: BFS requires more memory as it may need to store an entire level ($O(|V|)$), whereas DFS usually uses less ($O(\\log n)$ on average).\n4. **Optimality**: BFS guarantees the shortest path; DFS does not.\n\n### Visual Representation\n\n#### BFS\n\n![BFS Traversal](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2FBreadth-First-Search-Algorithm.gif?alt=media\u0026token=68f81a1c-00bc-4638-a92d-accdc257adc2)\n\n#### DFS\n  \n![DFS Traversal](https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/graph-theory%2FDepth-First-Search.gif?alt=media\u0026token=e0ce6595-d5d2-421a-842d-791eb6deeccb)\n\n### Code Example: BFS \u0026 DFS\n\nHere is the Python code:\n\n```python\n# BFS\ndef bfs(graph, start):\n    visited = set()\n    queue = [start]\n    while queue:\n        node = queue.pop(0)\n        if node not in visited:\n            visited.add(node)\n            queue.extend(graph[node] - visited)\n            \n# DFS\ndef dfs(graph, start, visited=None):\n    if visited is None:\n        visited = set()\n    visited.add(start)\n    for next_node in graph[start] - visited:\n        dfs(graph, next_node, visited)\n```\n\u003cbr\u003e\n\n## 13. Implement a method to check if there is a _Path between two vertices_ in a graph.\n\n### Problem Statement\n\nGiven an **undirected** graph, the task is to determine whether or not there is a **path** between two specified vertices.\n\n### Solution\n\nThe problem can be solved using **Depth-First Search (DFS)**.\n\n#### Algorithm Steps\n\n1. Start from the source vertex.\n2. For each adjacent vertex, if not visited, recursively perform DFS.\n3. If the destination vertex is found, return `True`. Otherwise, backtrack and explore other paths.\n\n#### Complexity Analysis\n\n- **Time Complexity**: $O(V + E)$  \n  $V$ is the number of vertices, and $E$ is the number of edges.\n- **Space Complexity**: $O(V)$  \n  For the stack used in recursive DFS calls.\n\n#### Implementation\n\nHere is the Python code:\n\n```python\nfrom collections import defaultdict\n\nclass Graph:\n    def __init__(self):\n        self.graph = defaultdict(list)\n\n    def add_edge(self, u, v):\n        self.graph[u].append(v)\n        self.graph[v].append(u)\n\n    def is_reachable(self, src, dest, visited):\n        visited[src] = True\n\n        if src == dest:\n            return True\n\n        for neighbor in self.graph[src]:\n            if not visited[neighbor]:\n                if self.is_reachable(neighbor, dest, visited):\n                    return True\n\n        return False\n\n    def has_path(self, src, dest):\n        visited = defaultdict(bool)\n        return self.is_reachable(src, dest, visited)\n\n# Usage\ng = Graph()\ng.add_edge(0, 1)\ng.add_edge(0, 2)\ng.add_edge(1, 2)\ng.add_edge(2, 3)\ng.add_edge(3, 3)\n\nsource, destination = 0, 3\nprint(f\"There is a path between {source} and {destination}: {g.has_path(source, destination)}\")\n```\n\u003cbr\u003e\n\n## 14. Solve the problem of printing all _Paths from a source to destination_ in a Directed Graph with BFS or DFS.\n\n### Problem Statement\n\nGiven a **directed graph** and two vertices $src$ and $dest$, the objective is to **print all paths** from $src$ to $dest$.\n\n### Solution\n\n1. **Recursive Depth-First Search (DFS)** Algorithm in Graphs: DFS is used because it can identify all the paths in a graph from source to destination. This is done by employing a **backtracking mechanism** to ensure that all unique paths are found.\n\n2. To deal with **cycles**, a list of visited nodes is crucial. By utilizing this list, the algorithm can avoid revisiting and getting stuck in an infinite loop.\n\n#### Complexity Analysis\n\n- **Time Complexity**: $O(V + E)$ \n  - $V$ is the number of vertices and $E$ is the number of edges. \n  - We're essentially visiting every node and edge once.\n\n- **Space Complexity**: $O(V)$\n  - In the worst-case scenario, the entire graph can be visited, which would require space proportional to the number of vertices. \n\n#### Implementation\n\nHere is the Python code:\n\n```python\n# Python program to print all paths from a source to destination in a directed graph\n\nfrom collections import defaultdict\n\n# A class to represent a graph\nclass Graph:\n    def __init__(self, vertices):\n        # No. of vertices\n        self.V = vertices\n\n        # default dictionary to store graph\n        self.graph = defaultdict(list)\n\n    def addEdge(self, u, v):\n        self.graph[u].append(v)\n\n    def printAllPathsUtil(self, u, d, visited, path):\n        # Mark the current node as visited and store in path\n        visited[u] = True\n        path.append(u)\n\n        # If current vertex is same as destination, then print current path\n        if u == d:\n            print(path)\n        else:\n            # If current vertex is not destination\n            # Recur for all the vertices adjacent to this vertex\n            for i in self.graph[u]:\n                if not visited[i]:\n                    self.printAllPathsUtil(i, d, visited, path)\n\n        # Remove current vertex from path and mark it as unvisited\n        path.pop()\n        visited[u] = False\n\n    # Prints all paths from 's' to 'd'\n    def printAllPaths(self, s, d):\n        # Mark all the vertices as not visited\n        visited = [False] * (self.V)\n\n        # Create an array to store paths\n        path = []\n        path.append(s)\n\n        # Call the recursive helper function to print all paths\n        self.printAllPathsUtil(s, d, visited, path)\n\n# Create a graph given in the above diagram\ng = Graph(4)\ng.addEdge(0, 1)\ng.addEdge(0, 2)\ng.addEdge(0, 3)\ng.addEdge(2, 0)\ng.addEdge(2, 1)\ng.addEdge(1, 3)\n\ns = 2 ; d = 3\nprint(\"Following are all different paths from %d to %d :\" %(s, d))\ng.printAllPaths(s, d)\n```\n\u003cbr\u003e\n\n## 15. What is a _Bipartite Graph_? How to detect one?\n\nA **bipartite graph** is one where the vertices can be divided into two distinct sets, $U$ and $V$, such that every edge connects a vertex from $U$ to one in $V$. The graph is denoted as $G = (U, V, E)$, where $E$ represents the set of edges.\n\n![Bipartite Graph Example](https://mathworld.wolfram.com/images/eps-gif/BipartiteGraph_1000.gif)\n\n### Detecting a Bipartite Graph\n\nYou can check if a graph is bipartite using several methods:\n\n#### Breadth-First Search (BFS)\n\nBFS is often used for this purpose. The algorithm colors vertices alternately so that no adjacent vertices have the same color.\n\n#### Code Example: Bipartite Graph using BFS\n\nHere is the Python code:\n\n```python\nfrom collections import deque\n\ndef is_bipartite_bfs(graph, start_node):\n    visited = {node: False for node in graph}\n    color = {node: None for node in graph}\n    color[start_node] = 1\n    queue = deque([start_node])\n\n    while queue:\n        current_node = queue.popleft()\n        visited[current_node] = True\n\n        for neighbor in graph[current_node]:\n            if not visited[neighbor]:\n                queue.append(neighbor)\n                color[neighbor] = 1 - color[current_node]\n            elif color[neighbor] == color[current_node]:\n                return False\n\n    return True\n\n# Example\ngraph = {'A': ['B', 'C'], 'B': ['A', 'C'], 'C': ['A', 'B', 'D'], 'D': ['C']}\nprint(is_bipartite_bfs(graph, 'A'))  # Output: True\n```\n\n#### Cycle Detection\n\nA graph is not bipartite if it contains an odd cycle. Algorithms like **DFS** or **Floyd's cycle-detection** algorithm can help identify such cycles.\n\u003cbr\u003e\n\n\n\n#### Explore all 50 answers here 👉 [Devinterview.io - Graph Data Structure](https://devinterview.io/questions/data-structures-and-algorithms/graph-data-structure-interview-questions)\n\n\u003cbr\u003e\n\n\u003ca href=\"https://devinterview.io/questions/data-structures-and-algorithms/\"\u003e\n\u003cimg src=\"https://firebasestorage.googleapis.com/v0/b/dev-stack-app.appspot.com/o/github-blog-img%2Fdata-structures-and-algorithms-github-img.jpg?alt=media\u0026token=fa19cf0c-ed41-4954-ae0d-d4533b071bc6\" alt=\"data-structures-and-algorithms\" width=\"100%\"\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fgraph-data-structure-interview-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevinterview-io%2Fgraph-data-structure-interview-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinterview-io%2Fgraph-data-structure-interview-questions/lists"}