FastPrepDijkstra Shortest Paths in a Weighted Undirected Graph
Problems/Dijkstra Shortest Paths in a Weighted Undirected Graph

Dijkstra Shortest Paths in a Weighted Undirected Graph

Goldman Sachs logoGoldman Sachs● MediumNEW GRADPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The reported task identifies this algorithmic exercise. The executable interface, bounds, deterministic tie rules, and examples are the documented practice contract.

You are given vertexCount vertices numbered from 0 to vertexCount - 1, an array of undirected weighted edges, and a source vertex. Each edge is [u, v, weight] with a nonnegative weight.

Return the shortest distance from source to every vertex in vertex order. Return -1 for an unreachable vertex. Parallel edges and self-loops are allowed, and all distance arithmetic must use signed 64-bit values.

Function

shortestUndirectedDistances(vertexCount: int, edges: int[][], source: int) → long[]

Examples

Example 1

vertexCount = 5edges = [[0,1,4],[0,2,1],[2,1,2],[1,3,1],[2,3,5]]source = 0return = [0,3,1,4,-1]

Vertex 1 is reached more cheaply through vertex 2, vertex 3 then follows through vertex 1, and vertex 4 is disconnected.

Example 2

vertexCount = 1edges = []source = 0return = [0]

The source has distance zero from itself.

Example 3

vertexCount = 4edges = [[0,1,10],[0,1,3],[1,2,0],[2,3,7],[0,3,20]]source = 0return = [0,3,3,10]

The lighter parallel edge reaches vertex 1, the zero-weight edge reaches vertex 2 at the same distance, and the best route to vertex 3 costs 10.

Constraints

  • 1 <= vertexCount <= 100000.
  • 0 <= edges.length <= 200000.
  • Every edge has valid endpoints and a weight in [0, 1000000000].
  • 0 <= source < vertexCount.
  • Every reachable shortest distance fits a signed 64-bit integer.

More Goldman Sachs problems

  • Palindrome CounterOA · Seen Oct 2026
  • Longest Palindromic SubsequenceOA · Seen Oct 2026
  • Best Average Student ScorePHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
All Goldman Sachs interview questionsSee Goldman Sachs hiring insights
Saved
class Solution {
    public long[] shortestUndirectedDistances(int vertexCount, int[][] edges, int source) {
      // write your code here
    }
}
Checking account…