KatInterview

877. Shortest Path Visiting All Nodes

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the shortest path in an undirected, connected graph that visits every single node. We are allowed to start and stop at any node, revisit nodes, and reuse edges. The number of nodes, n, is small (1 <= n <= 12), which is a strong hint that an algorithm with a time complexity exponential in n is acceptable.

Solution

Shortest Path Visiting All Nodes in Python

from collections import deque

class Solution:
    def shortestPathLength(self, graph: list[list[int]]) -> int:
        n = len(graph)
        if n <= 1:
            return 0

        # The target mask is when all bits from 0 to n-1 are set to 1.
        final_mask = (1 << n) - 1

        # Queue for BFS. Stores tuples of (node, mask).
        q = deque()

        # Visited set to avoid cycles. Stores tuples of (node, mask).
        visited = set()

        # Initialize the BFS. We can start from any node.
        # So, we add all nodes as potential starting points.
        for i in range(n):
            initial_mask = 1 << i
            q.append((i, initial_mask))
            visited.add((i, initial_mask))
        
        path_length = 0
        while q:
            level_size = len(q)
            for _ in range(level_size):
                u, mask = q.popleft()

                # If we've visited all nodes, we are done.
                if mask == final_mask:
                    return path_length

                # Explore neighbors.
                for v in graph[u]:
                    next_mask = mask | (1 << v)
                    
                    # If we have not visited this state (v, next_mask) before.
                    if (v, next_mask) not in visited:
                        visited.add((v, next_mask))
                        q.append((v, next_mask))
            
            path_length += 1
        
        return -1 # Should not be reached given constraints (connected graph).

Shortest Path Visiting All Nodes in Java

class Solution {
    public int shortestPathLength(int[][] graph) {
        int n = graph.length;
        if (n <= 1) {
            return 0;
        }

        // The target mask is when all bits from 0 to n-1 are set to 1.
        int finalMask = (1 << n) - 1;

        // Queue for BFS. Stores arrays of {node, mask}.
        Queue<int[]> q = new LinkedList<>();

        // Visited set to avoid cycles. A 2D array: visited[node][mask].
        boolean[][] visited = new boolean[n][1 << n];

        // Initialize the BFS. We can start from any node.
        // So, we add all nodes as potential starting points.
        for (int i = 0; i < n; i++) {
            int initialMask = 1 << i;
            q.offer(new int[]{i, initialMask});
            visited[i][initialMask] = true;
        }

        int pathLength = 0;
        while (!q.isEmpty()) {
            int levelSize = q.size();
            pathLength++; // Each level corresponds to one step in the path.

            for (int i = 0; i < levelSize; i++) {
                int[] currentState = q.poll();
                int u = currentState[0];
                int mask = currentState[1];

                // Explore neighbors.
                for (int v : graph[u]) {
                    int nextMask = mask | (1 << v);

                    // If we've visited all nodes, we are done.
                    if (nextMask == finalMask) {
                        return pathLength;
                    }

                    // If we have not visited this state (v, nextMask) before.
                    if (!visited[v][nextMask]) {
                        visited[v][nextMask] = true;
                        q.offer(new int[]{v, nextMask});
                    }
                }
            }
        }

        return 0; // Should not be reached given constraints (connected graph).
    }
}

Shortest Path Visiting All Nodes in C++

class Solution {
public:
    int shortestPathLength(vector<vector<int>>& graph) {
        int n = graph.size();
        if (n <= 1) {
            return 0;
        }

        // The target mask is when all bits from 0 to n-1 are set to 1.
        int finalMask = (1 << n) - 1;

        // Queue for BFS. Stores pairs of {node, mask}.
        queue<pair<int, int>> q;

        // Visited set to avoid cycles. A 2D array: visited[node][mask].
        vector<vector<bool>> visited(n, vector<bool>(1 << n, false));

        // Initialize the BFS. We can start from any node.
        // So, we add all nodes as potential starting points.
        for (int i = 0; i < n; ++i) {
            int initialMask = 1 << i;
            q.push({i, initialMask});
            visited[i][initialMask] = true;
        }

        int pathLength = 0;
        while (!q.empty()) {
            int levelSize = q.size();
            pathLength++; // Each level corresponds to one step in the path.

            for (int i = 0; i < levelSize; ++i) {
                pair<int, int> currentState = q.front();
                q.pop();
                int u = currentState.first;
                int mask = currentState.second;

                // Explore neighbors.
                for (int v : graph[u]) {
                    int nextMask = mask | (1 << v);

                    // If we've visited all nodes, we are done.
                    // The path length is the current number of steps.
                    if (nextMask == finalMask) {
                        return pathLength;
                    }

                    // If we have not visited this state (v, nextMask) before.
                    if (!visited[v][nextMask]) {
                        visited[v][nextMask] = true;
                        q.push({v, nextMask});
                    }
                }
            }
        }

        return 0; // Should not be reached given the problem constraints (connected graph).
    }
};

Shortest Path Visiting All Nodes in TypeScript

function shortestPathLength(graph: number[][]): number {
    const n = graph.length;
    if (n <= 1) {
        return 0;
    }

    // The target mask is when all bits from 0 to n-1 are set to 1.
    const finalMask = (1 << n) - 1;

    // Queue for BFS. Stores tuples of [node, mask].
    const queue: [number, number][] = [];

    // Visited set to avoid cycles. A 2D array: visited[node][mask].
    const visited: boolean[][] = Array(n).fill(0).map(() => Array(1 << n).fill(false));

    // Initialize the BFS. We can start from any node.
    // So, we add all nodes as potential starting points.
    for (let i = 0; i < n; i++) {
        const initialMask = 1 << i;
        queue.push([i, initialMask]);
        visited[i][initialMask] = true;
    }

    let pathLength = 0;
    while (queue.length > 0) {
        const levelSize = queue.length;
        for (let i = 0; i < levelSize; i++) {
            const [u, mask] = queue.shift()!;

            // If we've visited all nodes, we are done.
            if (mask === finalMask) {
                return pathLength;
            }

            // Explore neighbors.
            for (const v of graph[u]) {
                const nextMask = mask | (1 << v);

                // If we have not visited this state (v, nextMask) before.
                if (!visited[v][nextMask]) {
                    visited[v][nextMask] = true;
                    queue.push([v, nextMask]);
                }
            }
        }
        pathLength++;
    }

    return -1; // Should not be reached given constraints (connected graph).
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.