Shortest Distance in an Unweighted Adjacency-Matrix Graph
Last updated: August 16, 2026
Quick Overview
The question asks the candidate to find the shortest distance between two nodes in an unweighted graph represented by an adjacency matrix.
BCG
August 16, 20260
0
2 solved
The question asks the candidate to find the shortest distance between two nodes in an unweighted graph represented by an adjacency matrix.
This question is typically asked during the technical screen round for engineering roles, particularly those focused on algorithmic problem-solving. Interviewers use this question to evaluate the candidate's understanding of graph traversal algorithms, specifically how well they can implement a solution using breadth-first search (BFS) or depth-first search (DFS) to find the shortest path in an unweighted graph.
What the Interviewer Expects
- Correctly identify that BFS is the appropriate algorithm for this problem.
- Implement the algorithm efficiently using the adjacency matrix.
- Handle edge cases such as disconnected nodes or invalid input gracefully.
- Explain the time and space complexity of the implemented solution.
- Provide a clear and structured code solution with comments.
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would your approach change if the graph were weighted?
- Can you explain the time and space complexity of your solution?
- What other algorithms could be used to solve this problem?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Approach
To find the shortest distance in an unweighted graph, we can utilize the Breadth-First Search (BFS) algorithm. BFS is ideal for this scenario because it explores all neighbors at the present depth pri...
Algorithm
- Initialize a queue to keep track of nodes to explore.
- Create a distance array to store the shortest distance from the source node to each node, initialized to a large value (infinity).
- Set th...