Shortest Path Visiting All Nodes
Updated
Problem statement
You are given a connected, undirected graph with n nodes labeled from 0 to n - 1. The adjacency list graph[i] contains every node joined to node i by an edge.
Return the minimum number of edges in a walk that visits every node at least once. You may start and finish at any node, revisit nodes, and traverse an edge more than once.
Function
shortestPathLength(graph: int[][]) → intExamples
Example 1
graph = [[1,2,3],[0],[0],[0]]return = 4One shortest walk is 1 - 0 - 2 - 0 - 3, which uses four edges.
Example 2
graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]return = 4A four-edge walk such as 0 - 1 - 4 - 2 - 3 visits all five nodes.
Constraints
1 <= n <= 12graph.length == n0 <= graph[i].length < ngraph[i]does not containior duplicate neighbors.- If
jappears ingraph[i], theniappears ingraph[j]. - The graph is connected.
More InMobi Onsite Interview questions
- Russian Doll EnvelopesONSITE INTERVIEW · Seen Jul 2026
- Minimum and Maximum with Optimal ComparisonsONSITE INTERVIEW · Seen Dec 2025
- Minimum Edges to Connect All ComponentsONSITE INTERVIEW · Seen Dec 2025
- Maximum Sum of Non-Adjacent Tree NodesONSITE INTERVIEW · Seen Jan 2022
- Word SquaresONSITE INTERVIEW · Seen Jan 2022
- Maximum Length Pair ChainONSITE INTERVIEW · Seen Jul 2021
- Top View of a Binary TreeONSITE INTERVIEW · Seen Jul 2021
- Maximum XOR Between Two ArraysONSITE INTERVIEW · Seen May 2021
- Trapping Rain WaterONSITE INTERVIEW · Seen May 2021
- Validate Binary Search TreeONSITE INTERVIEW · Seen May 2021
Similar questions at other companies
- Shortest Round Trip Through All DeliveriesGoogle · ONSITE INTERVIEWGoogle interview questions
- Minimum Distance Matching in a ForestScale AI · PHONE SCREEN · ONSITE INTERVIEWScale AI interview questions
- Grid Robot Route with Charging PrioritiesUber · PHONE SCREEN · ONSITE INTERVIEWUber interview questions
- Maximum Currency Conversion Along a Simple PathRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions
- Minimum Semesters With Course CapacityAmazon · ONSITE INTERVIEW
- Drone Delivery with Battery Swap StationsCisco · OACisco interview questions
- Longest Anchored Song ChainIntuit · OAIntuit interview questions
- Cheapest Visiting Order with PrerequisitesIndeed · OAIndeed interview questions
- Minimum Semesters with a Course LimitSnowflake · PHONE SCREENSnowflake interview questions
- Count Routes Through Four Shop TypesOpenAI · OAOpenAI interview questions