DSA interview question
A social app shows "people you may know" by exploring the network outward in rings: first your direct friends, then their friends, and so on. That's breadth-first search. Starting from vertex 0, a queue holds discovered-but-unprocessed vertices. Each vertex is marked visited when it's enqueued, so it's never added twice, and neighbours are explored in the order they appear in the adjacency list. The visit order lists vertices by increasing distance from the start.
Example: adjacency [[1,2,3], [], [4], [], []] → [0, 1, 2, 3, 4].
vector<int> bfsOfGraph(const vector<vector<int>>& adj); // start at vertex 0
| Input (adjacency list) | Output | Explanation |
|---|---|---|
[[1,2,3], [], [4], [], []] | [0, 1, 2, 3, 4] | 4 is two steps away |
[[1,2], [0,3], [0,3], [1,2]] | [0, 1, 2, 3] | A square: 3 is reached once |
[[2], [2], [0,1]] | [0, 2, 1] | |
[[1], [0,2], [1]] | [0, 1, 2] | A path |
[[]] | [0] |
(Confirm: neighbours are explored in list order; only vertices reachable from 0 appear.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in