FastPrepShortest Path from Encoded Graph Edges

Shortest Path from Encoded Graph Edges

BitGo logoBitGo● MediumFULLTIMEOA
Learn

Problem statement

You are given an array edges describing an unweighted, undirected graph. Each entry has the exact form "u,v", where u and v are nonnegative decimal node labels.

Parse the edges and return the minimum number of edges on any path from source to target.

  • Duplicate edges and self-loops may appear and do not change the answer.
  • When source equals target, return 0.
  • When target is unreachable, return -1.

Function

shortestHopDistance(edges: String[], source: int, target: int) → int

Examples

Example 1

edges = ["0,1","1,2","0,3","3,2"]source = 0target = 2return = 2

Both 0 → 1 → 2 and 0 → 3 → 2 use two edges, so the shortest-hop distance is 2.

Example 2

edges = ["10,11","12,13"]source = 10target = 13return = -1

The source and target belong to different connected components.

Constraints

  • 0 <= edges.length <= 200000.
  • Every edge is exactly two decimal integers separated by one comma, with no spaces.
  • Every node label, source, and target is between 0 and 1000000000.

More BitGo problems

See BitGo hiring insights
public int shortestHopDistance(String[] edges, int source, int target) {
    // Write your code here.
}
edges["0,1","1,2","0,3","3,2"]
source0
target2
expected2
Checking account…