FastPrepShortest Distance in a Graph

Shortest Distance in a Graph

Zip logoZip● MediumNEW GRADPHONE SCREEN
Learn

Problem statement

You are given an undirected, unweighted graph with n vertices labeled from 0 through n - 1. Each pair [u, v] in edges connects vertices u and v in both directions.

Return the minimum number of edges in a path from start to target. Return -1 if no such path exists.

  • Every edge takes one step to traverse.
  • If start equals target, return 0.
  • The graph may be disconnected or contain cycles. Duplicate edges and self-loops are allowed; they do not create a shorter route.
  • Return only the minimum distance, not the sequence of vertices.

Function

shortestDistance(n: int, edges: int[][], start: int, target: int) → int

Examples

Example 1

n = 6edges = [[0,1],[1,2],[2,5],[0,3],[3,5],[3,4]]start = 0target = 5return = 2

The path 0 -> 3 -> 5 uses two edges. No edge connects 0 directly to 5, so a one-edge path is impossible.

Example 2

n = 5edges = [[0,1],[1,2],[3,4]]start = 0target = 4return = -1

Vertices 0 and 4 belong to different connected components, so the result is -1.

Example 3

n = 3edges = [[0,1]]start = 2target = 2return = 0

The start is already the target. No edge needs to be traversed, even though vertex 2 is isolated.

Constraints

  • 1 <= n <= 20000
  • 0 <= edges.length <= 100000
  • Every edge contains exactly two vertex labels.
  • For every edge [u, v], 0 <= u, v < n.
  • 0 <= start, target < n

More Zip problems

See Zip hiring insights
public int shortestDistance(int n, int[][] edges, int start, int target) {
    // Write your code here.
}
n6
edges[[0,1],[1,2],[2,5],[0,3],[3,5],[3,4]]
start0
target5
expected2
Checking account…