WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Tree and Graph Problems · question 63 of 120

How would you implement a Depth-First Search on a graph?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. Starting at the root (in case of a tree) or an arbitrary node (in case of a graph), the algorithm explores as far as possible along each branch before backtracking.

Here is a high-level DFS algorithm:

DFS(node):
  if node is visited:
    return
  mark node as visited
  for each neighbor of node:
    DFS(neighbor)

To implement DFS, we typically use a stack data structure.

Here’s some pseudo-code that implements DFS with a stack to track the traversal:

DFS-iterative(node):
  create a stack S and push node into it
  mark node as visited
  while S is not empty:
    v = S.pop()         # Pop a vertex from stack to visit next
    visit(v)
    for each neighbor x of v:
      if x is not visited:
        push x into S
        mark x as visited 

We assume the presence of a helper function ‘visit(v)‘, which handles the logic to be performed when visiting node ‘v‘.

Let’s take an example graph:

{1: [2, 3], 2: [4, 5], 3: [], 4: [], 5: []}

This can be visualized as:

1
/ \
2   3
/ \
4   5

If we start our DFS from node 1, the order of traversal will be ‘1-2-4-5-3‘.

To improve this pseudo-code, you would also typically create a ‘Node‘ object that has a ‘visited‘ field, rather than marking them as visited externally.

It’s also worth noting that in terms of time complexity, DFS takes O(V + E) time, where V is the number of vertices and E is the number of edges, because every vertex and every edge will be explored in the worst case. DFS takes O(V) space, due to the storage required for the stack and the visited map.

Please note that this is a high level overview of DFS and, depending on the specifics of your graph and the problem at hand, you might need to adapt it.

Unfortunately, charts and mathematical formulas are not typically used in the explanation of Depth-First Search implementation, because it is primarily a procedural concept and therefore can best be described in the form of these procedural pseudo-code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics