Back to Practice
#0167

Shortest Path in an Unweighted Graph

MediumDSA25 min20 XP

Problem

Given an adjacency list graph, start node, and target node, return the shortest number of edges. Return -1 if unreachable.

Why This Matters

BFS shortest path is a core graph pattern behind routing, social distance, and state-space search.

Function Signature

def shortest_path_length(graph, start, target):

Examples

Example 1
Input{'A':['B','C'], 'B':['D'], 'C':['D'], 'D':[]}, start='A', target='D'
Output2

A -> B -> D or A -> C -> D uses two edges.

Constraints

  • Return the exact requested output.
  • Handle ordinary edge cases.
  • Prefer simple, interview-readable code.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Input{'A':['B','C'], 'B':['D'], 'C':['D'], 'D':[]}, start='A', target='D'
Expected2

A -> B -> D or A -> C -> D uses two edges.

Hidden Test Categories
empty or minimal inputduplicates or tieslarger input