Shortest Path Visiting All Nodes

HardGraphsBFS

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

Examples

Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
One possible path is [1,0,2,0,3].
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4

Constraints

  • n == graph.length
  • 1 <= n <= 12
  • 0 <= graph[i].length < n
  • The input graph is always connected.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More BFS problems