Shortest Hop Path Between Machines
Updated
Problem statement
A data center contains n machines numbered from 0 through n - 1. Each pair connections[i] = [u, v] is a bidirectional connection between machines u and v. Every connection takes one hop.
Return a path from source to target that uses the minimum possible number of hops, including both endpoints. If several shortest paths exist, return the lexicographically smallest machine sequence. If the target is unreachable, return an empty array.
When source == target, return the one-machine path [source].
Function
shortestMachinePath(n: int, connections: int[][], source: int, target: int) → int[]Examples
Example 1
n = 6connections = [[0,2],[2,5],[0,1],[1,5],[1,3],[3,4]]source = 0target = 5return = [0,1,5]Paths [0, 1, 5] and [0, 2, 5] both use two hops. The path through machine 1 is lexicographically smaller.
Example 2
n = 4connections = [[0,1],[2,3]]source = 0target = 3return = []The source and target lie in different connected components, so no path exists.
Constraints
1 <= n <= 200000.0 <= connections.length <= 300000.- Every connection contains two distinct machine IDs in
[0, n - 1]. - No undirected connection appears more than once.
0 <= source, target < n.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Shortest Increasing Path to a TargetUber · ONSITE INTERVIEWUber interview questions
- Find and Reconstruct a Binary-Matrix PathMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Shortest Distance from All BuildingsWaymo · PHONE SCREENWaymo interview questions
- Cheapest Flights Within K StopsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Fire Station Response BillLinkedIn · ONSITE INTERVIEWLinkedIn interview questions
- Island Count and Maximum AreaOracle · ONSITE INTERVIEWOracle interview questions
- Minimum Friend API CallsMercor · ONSITE INTERVIEWMercor interview questions
- Cheapest Flights Within K StopsGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Open the Lock and Return a Shortest PathZip · PHONE SCREEN · ONSITE INTERVIEWZip interview questions
- Max Area of IslandRoku · ONSITE INTERVIEWRoku interview questions