Shortest-Path Distances with Dijkstra
Updated
Problem statement
You are given a directed graph with n vertices numbered from 0 to n - 1. Each edge [u,v,w] permits travel from u to v with nonnegative cost w. Parallel edges and self-loops are allowed.
Return an array of length n where entry v is the minimum total cost of a path from source to v. Return -1 for an unreachable vertex. The distance from the source to itself is 0, using the empty path.
Any correct method within the bounds is accepted; a heap is not required.
Function
shortestDistances(n: int, edges: int[][], source: int) → int[]Examples
Example 1
n = 4edges = [[0,1,4],[0,2,1],[2,1,2],[1,3,1],[2,3,5]]source = 0return = [0,3,1,4]The best routes to vertices 1 and 3 go through vertex 2.
Example 2
n = 3edges = [[1,2,5]]source = 1return = [-1,0,5]Vertex 0 is unreachable from 1. The empty route from the source to itself has distance zero.
Constraints
1 <= n <= 200.0 <= edges.length <= 1000.- Every edge has exactly three integers;
0 <= u,v < nand0 <= w <= 10^6. 0 <= source < n.
More Apple Phone Screen questions
- Topological OrderingPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- LRU CachePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Merge IntervalsOA · PHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Subarray Product Less Than KPHONE SCREEN · Seen Nov 2026
- Evaluate DivisionPHONE SCREEN · Seen Nov 2026
- Reverse a Linked ListPHONE SCREEN · Seen Nov 2026
- Validate a BST with a Custom ComparisonPHONE SCREEN · Seen Nov 2026
- Design a Food Rating SystemPHONE SCREEN · Seen Oct 2026
- Days Until Poisoned Plants StabilizePHONE SCREEN · Seen Oct 2026
- Capture Surrounded Regions with Union-FindPHONE SCREEN · Seen Oct 2026
Similar questions at other companies
- Shortest Travel Time in a Grid with Traffic LightsWaymo · PHONE SCREENWaymo interview questions
- Cheapest Flights Within K StopsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Shortest Paths in a Nonnegative Directed GraphNation with NaMo · PHONE SCREEN
- Maximum-Efficiency Transmission PathGoogle · PHONE SCREENGoogle interview questions
- Dijkstra Shortest Paths in a Weighted Undirected GraphGoldman Sachs · PHONE SCREENGoldman Sachs interview questions
- Shortest Path with Directional Move CostsThe Walt Disney Company · PHONE SCREENThe Walt Disney Company interview questions
- Fastest Flight Route Between AirportsAirbnb · PHONE SCREENAirbnb interview questions
- Dynamic Broadcast TimesNetflix · PHONE SCREENNetflix interview questions
- Path With Maximum ProbabilitySalesforce · ONSITE INTERVIEWSalesforce interview questions
- Minimum Stress PathWalmart · OAWalmart interview questions