FastPrepPrint a Shortest Graph Path

Print a Shortest Graph Path

Amazon logoAmazon● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given n vertices and directed edges, return the lexicographically smallest vertex sequence among all shortest paths from source to target.

Function

shortestPath(n: int, edges: int[][], source: int, target: int) → int[]

Examples

Example 1

n = 5edges = [[0,1],[0,2],[1,4],[2,4]]source = 0target = 4return = [0,1,4]

Both paths have two edges, and the path through one is lexicographically smaller.

Example 2

n = 4edges = [[0,1]]source = 0target = 3return = []

The target is unreachable.

Constraints

  • 1 <= n <= 100000
  • Edges contain valid vertex indices.
  • Duplicate edges and self-loops may appear.

More Amazon problems

See Amazon hiring insights
public int[] shortestPath(int n, int[][] edges, int source, int target) {
  // Write your code here.
}
n5
edges[[0,1],[0,2],[1,4],[2,4]]
source0
target4
expected[0,1,4]
Checking account…