Shortest Path in Unweighted Graph

Problem

Return the shortest path length between nodes in an unweighted adjacency list, or -1.

Examples

Example 1
Input: {"graph":[[1,2],[0,3],[0,3],[1,2]],"start":0,"end":3}
Output: 2
Example 2
Input: {"graph":[[1],[0],[]],"start":0,"end":2}
Output: -1

Input and output use JSON-compatible values. For linked-list and tree questions, arrays represent the node structure as described above. Your code should implement solve(input).

Write your solutionImplement solve(input). Your draft is saved in this browser.
Advertisement

How to solve Shortest Path in Unweighted Graph

Return the shortest path length between nodes in an unweighted adjacency list, or -1. Breadth-first search visits nodes in order of increasing distance. The reference implementation illustrates this approach; check the example and edge cases.

Time and space complexity

O(V+E) time and O(V) space.

Practise and improve

Choose JavaScript, TypeScript or Python, complete the starter code, then select Run Tests. Request a hint when you need guidance, or choose View solution and confirm if you would like to study the reference implementation.