DSA interview question
A maze-solving robot explores corridors by going as deep as possible down one path before backing up to try the next branch. That's depth-first search. Starting at vertex 0, visit a vertex, then recursively visit its first unvisited neighbour, going all the way down, then its next unvisited neighbour, and so on. The recursion (or an explicit stack) remembers where to back up to, and a visited array stops the robot from going round in circles.
Example: adjacency [[2,3,1], [0], [0,4], [0], [2]] → [0, 2, 4, 3, 1].
vector<int> dfsOfGraph(const vector<vector<int>>& adj); // start at vertex 0
| Input (adjacency list) | Output | Explanation |
|---|---|---|
[[2,3,1], [0], [0,4], [0], [2]] | [0, 2, 4, 3, 1] | 4 is reached through 2 before 3 is tried |
[[1,2], [0,2], [0,1,3,4], [2], [2]] | [0, 1, 2, 3, 4] | |
[[1], [0]] | [0, 1] | |
[[1,2], [0], [0]] | [0, 1, 2] | Back up to 0, then 2 |
[[]] | [0] |
(Confirm: neighbours are tried 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