As reported: LinkedIn Senior Software Engineer, Systems & Infrastructure (Bangalore, Mar 2025), onsite DSA round 4: Max Consecutive Ones III, then a graph question — the shortest path between a node and a target, printing the path.
You are given an undirected, unweighted graph with nodes 1 … n and a list of edges, plus two nodes source and target. Return a shortest path from source to target as the list of nodes along it (starting with source, ending with target). If target cannot be reached, return an empty list.
Example 1
n = 6
edges = [[1,2],[2,3],[3,6],[1,4],[4,5],[5,6],[2,5]]
source = 1, target = 6
Output: [1,2,3,6] ([1,2,5,6] and [1,4,5,6] are also correct)
Example 2
n = 4, edges = [[1,2],[3,4]], source = 1, target = 4
Output: []
Example 3
n = 3, edges = [[1,2],[2,3]], source = 2, target = 2
Output: [2]
Constraints: 1 ≤ n ≤ 2·10^4; 0 ≤ edges.length ≤ 4·10^4; edges[i] = [u, v] with 1 ≤ u, v ≤ n, u ≠ v; an edge may appear more than once; 1 ≤ source, target ≤ n.
Clarifications
- Every edge has the same length, so "shortest" means fewest edges.
- When several shortest paths exist, any of them is accepted.
Code runner format: LeetCode's test-case format, one JSON value per line (one line per argument). Implement shortestPath(n, edges, source, target). The harness checks that the returned list is a path from source to target along the edges and prints its number of edges (-1 for an empty list); the expected value is the shortest distance.