Implement a Graph (Adjacency Matrix)

Data Structures
Medium
Airbnb
68.5K views

Design a graph data structure using an Adjacency Matrix. Implement methods for adding edges and checking if a path exists between two nodes.

Why Interviewers Ask This

Interviewers at Airbnb ask this to evaluate your ability to select appropriate data structures for specific constraints. They want to see if you understand the trade-offs between space and time complexity, specifically how an adjacency matrix handles dense graphs versus sparse ones. This tests your foundational knowledge of graph algorithms and your capacity to implement robust, error-free code under pressure.

How to Answer This Question

1. Clarify requirements immediately: Ask about node count limits and whether the graph is directed or weighted, as Airbnb values clarity in ambiguous scenarios. 2. Define the structure: Propose a 2D array where indices represent nodes and values represent edge weights or existence flags. Mention O(1) lookup benefits. 3. Discuss complexity trade-offs: Explicitly state that while checking edges is O(1), space usage is O(V^2), making it unsuitable for very large, sparse networks like global flight routes but ideal for smaller social clusters. 4. Implement core methods: Walk through adding an edge by updating two matrix cells (for undirected) or one (directed). For path finding, suggest Breadth-First Search (BFS) using a queue and a visited set. 5. Validate with examples: Trace a small example manually to show how the matrix updates and how BFS traverses neighbors row by row until the target is found.

Key Points to Cover

  • Explicitly discussing the O(V^2) space complexity trade-off compared to adjacency lists
  • Demonstrating understanding of directed vs. undirected graph updates in the matrix
  • Selecting BFS as the optimal traversal algorithm for path existence checks
  • Clarifying assumptions about node counts before writing code
  • Handling edge cases like self-loops or disconnected components

Sample Answer

To design a graph using an adjacency matrix, I would start by initializing a 2D integer array of size V x V, where V is the number of vertices. Each cell [i][j] will store the weight of the edge from node i to j; if no edge exists, we can store infinity or zero depending on the problem context. For the addEdge method, if the graph is directed, I simply assign the weight to matrix[source][destination]. If undirected, I update both matrix[source][destination] and matrix[destination][source] to maintain symmetry. This operation runs in constant time, O(1). To check for a path, I would use Breadth-First Search since we need the shortest unweighted path or just reachability. I'll initialize a queue with the starting node and a boolean array to track visited nodes. While the queue isn't empty, I dequeue a node and iterate through its entire row in the matrix. For every column index representing a neighbor, if an edge exists and the neighbor hasn't been visited, I mark it visited and enqueue it. If I encounter the destination node during this process, I return true immediately. If the queue empties without finding the target, the path doesn't exist. This approach ensures O(V^2) time complexity due to the matrix iteration, which is acceptable for dense graphs typical in internal recommendation systems where connectivity is high.

Common Mistakes to Avoid

  • Failing to mention that adjacency matrices are inefficient for sparse graphs with few edges
  • Implementing DFS instead of BFS without explaining why, potentially missing the shortest path logic
  • Neglecting to handle the symmetric update for undirected graphs when adding edges
  • Not defining what value represents 'no edge' (e.g., -1, 0, or infinity) leading to logical errors

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 154 Data Structures questionsBrowse all 33 Airbnb questions