ORIGINAL CODING QUESTION
Fewest connection hops
Given an undirected unweighted graph, return the fewest edges from source to target, or -1 if unreachable. Duplicate edges and self-loops are allowed.
Original exercise · medium. Editorial role relevance does not imply a company has asked this question.
Input and output
n m, then m pairs of zero-based vertex IDs, then source target. Print the shortest distance.
Constraints
1 ≤ n ≤ 2,000; 0 ≤ m ≤ 10,000; all vertices are in [0, n).
Example 1
Input
4 3 0 1 1 2 2 3 0 3
Output
3
Three edges connect 0 to 3.
Example 2
Input
4 1 0 1 0 3
Output
-1
Vertex 3 is unreachable from 0.
Explain your approach
Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?
Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.
Hint 1
All edges have the same cost.
Hint 2
Breadth-first search visits vertices in distance order.
Hint 3
Mark a vertex when enqueuing it, not when removing it, to avoid duplicate work.
Practice this question
Save your work privately, explain decisions and return to your revision queue.
Open practice workspaceBrowse the question library →