← All Exercises

Iterative DFS Preorder on an Adjacency Map

basictypescript~25min

Background

Explicit-stack DFS is required in runtimes with small call stacks and is the basis for iterative topological sorting and maze solving.

Problem

Given an adjacency map and a start node, return the preorder DFS traversal using an explicit stack so deep graphs cannot overflow the call stack.

Input

A record mapping node names to arrays of neighbor names, plus a start node that may be absent from the map.

Output

An array of node names in the order first visited, each appearing once.

Sample tests

Sample 1

Input: graph = {A:["B","C"],B:["D"],C:["D"],D:[]}, start = "A"
Expected: ["A","B","D","C"]

Sample 2

Input: graph = {A:["B"],B:["A"]}, start = "A"
Expected: ["A","B"]

Sample 3

Input: graph = {}, start = "Z"
Expected: ["Z"]

Your solution

Learning objective

Simulate recursive DFS with a stack, reverse neighbor pushes for ordering, and guard cycles with a visited set.