DSA Tracker

Problem

Medium

Shortest Path in Directed Acyclic Graph

A medium Graph interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Graph
Sheets
1
Core for
12 roles

The problem

Given a directed acyclic graph with n vertices and a list of weighted edges [u, v, weight], and a source vertex, find the shortest path distances from the source to all other vertices using topological sorting.

Example 1

Input
n = 6, edges = [[0,1,5],[0,2,3],[1,3,6],[2,4,4],[3,5,1],[4,5,1]], source = 0
Output
[0,5,3,11,7,5]
Why
Shortest paths from 0 to all nodes using topological order.

Example 2

Input
n = 3, edges = [[0,1,2],[1,2,3]], source = 0
Output
[0,2,5]
Why
Path 0->1->2 gives distances 2 and 5.

Constraints

  • 1 <= n <= 100
  • 0 <= edges.length <= n * (n - 1)
  • 1 <= edge weight <= 1000

How to think about it

Updated 2026-09-29

In a directed acyclic graph, cycles are impossible, which means vertices can be sorted in strict topological order. If you process vertices in topological order, by the time you arrive at vertex u, its shortest path distance is permanently finalized because no subsequent vertex can ever loop back to affect it. This achieves shortest path in linear time without priority queues.

Approaches, worst first

  1. Standard Bellman-Ford relaxation

    time O(V * E) · space O(V)

    Relax all edges repeatedly across V - 1 full passes starting from the source vertex. While Bellman-Ford correctly finds shortest paths even with negative edge weights, it ignores topological ordering and requires O(V * E) time instead of a single linear pass.

  2. Topological order single-pass relaxationWrite this one

    time O(V + E) · space O(V + E)

    Find a topological ordering of the DAG using DFS or Kahn's algorithm. Initialize `dist` array to infinity with `dist[source] = 0`. Iterate through the topological ordering: for each vertex u, if `dist[u] !== inf`, relax all outgoing edges `(u, v, weight)` setting `dist[v] = min(dist[v], dist[u] + weight)`.

Where people lose marks · 3
  • Skipping the check `dist[u] !== inf` before relaxing outgoing edges; relaxing from unreachable nodes propagates invalid arithmetic.
  • Vertices that appear before `source` in the topological sort order cannot be reached from `source` and must remain at infinity.
  • Assuming the graph has a source with in-degree 0; the given starting node may have incoming edges from predecessor components.

Full solution

C++
#include <bits/stdc++.h>
using namespace std;

static void topoDfs(int u, const vector<vector<pair<int, int>>>& adj, vector<bool>& visited, vector<int>& stack) {
    visited[u] = true;
    for (const auto& edge : adj[u]) {
        if (!visited[edge.first]) {
            topoDfs(edge.first, adj, visited, stack);
        }
    }
    stack.push_back(u);
}

vector<int> shortestPath(int n, int m, vector<vector<int>>& edges) {
    vector<vector<pair<int, int>>> adj(n);
    for (const auto& e : edges) {
        adj[e[0]].push_back({e[1], e[2]});
    }
    vector<bool> visited(n, false);
    vector<int> stack;
    for (int i = 0; i < n; i++) {
        if (!visited[i]) topoDfs(i, adj, visited, stack);
    }
    const int INF = 1e9;
    vector<int> dist(n, INF);
    dist[0] = 0;
    while (!stack.empty()) {
        int u = stack.back();
        stack.pop_back();
        if (dist[u] != INF) {
            for (const auto& edge : adj[u]) {
                int v = edge.first, w = edge.second;
                if (dist[u] + w < dist[v]) {
                    dist[v] = dist[u] + w;
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        if (dist[i] == INF) dist[i] = -1;
    }
    return dist;
}
Java
import java.util.*;

public class Main {
    static void topoDfs(int u, List<List<int[]>> adj, boolean[] visited, List<Integer> stack) {
        visited[u] = true;
        for (int[] edge : adj.get(u)) {
            if (!visited[edge[0]]) {
                topoDfs(edge[0], adj, visited, stack);
            }
        }
        stack.add(u);
    }

    static int[] shortestPath(int n, int m, int[][] edges) {
        List<List<int[]>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (int[] e : edges) {
            adj.get(e[0]).add(new int[]{e[1], e[2]});
        }
        boolean[] visited = new boolean[n];
        List<Integer> stack = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (!visited[i]) topoDfs(i, adj, visited, stack);
        }
        final int INF = 1000000000;
        int[] dist = new int[n];
        Arrays.fill(dist, INF);
        dist[0] = 0;
        for (int i = stack.size() - 1; i >= 0; i--) {
            int u = stack.get(i);
            if (dist[u] != INF) {
                for (int[] edge : adj.get(u)) {
                    int v = edge[0], w = edge[1];
                    if (dist[u] + w < dist[v]) {
                        dist[v] = dist[u] + w;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) {
            if (dist[i] == INF) dist[i] = -1;
        }
        return dist;
    }
}
Python
def shortest_path(n, m, edges):
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))

    visited = [False] * n
    stack = []

    def topo_dfs(u):
        visited[u] = True
        for v, w in adj[u]:
            if not visited[v]:
                topo_dfs(v)
        stack.append(u)

    for i in range(n):
        if not visited[i]:
            topo_dfs(i)

    dist = [float('inf')] * n
    dist[0] = 0

    while stack:
        u = stack.pop()
        if dist[u] != float('inf'):
            for v, w in adj[u]:
                if dist[u] + w < dist[v]:
                    dist[v] = dist[u] + w

    return [d if d != float('inf') else -1 for d in dist]
JavaScript
function shortestPath(n, m, edges) {
  const adj = Array.from({ length: n }, () => []);
  const inDegree = Array(n).fill(0);
  for (const [u, v, w] of edges) {
    adj[u].push([v, w]);
    inDegree[v]++;
  }

  const queue = [];
  for (let i = 0; i < n; i++) {
    if (inDegree[i] === 0) queue.push(i);
  }

  const topo = [];
  let head = 0;
  while (head < queue.length) {
    const u = queue[head++];
    topo.push(u);
    for (const [v, w] of adj[u]) {
      inDegree[v]--;
      if (inDegree[v] === 0) queue.push(v);
    }
  }

  const dist = Array(n).fill(Infinity);
  dist[0] = 0;

  for (const u of topo) {
    if (dist[u] !== Infinity) {
      for (const [v, w] of adj[u]) {
        if (dist[u] + w < dist[v]) {
          dist[v] = dist[u] + w;
        }
      }
    }
  }

  return dist.map(d => (d === Infinity ? -1 : d));
}
Try it in the editor

The theory behind it

Graph — the ground this problem stands on. All Graph problems

What Graph is

A graph is a network of individual points, called vertices or nodes, connected by lines called edges. Think of a subway transit map, an electrical circuit, or a web of social friends. Unlike a tree, a graph has no designated top node and no parent-child hierarchy. Connections can run one-way or both ways, and paths can loop back on themselves to form closed cycles.

When to reach for it

Reach for graph algorithms when inputs describe relationships, networks, flights between cities, course prerequisites, or clone networks. Signals include finding the shortest route across unweighted connections, ordering tasks that depend on earlier tasks, counting isolated clusters, or checking whether a path contains an infinite loop. Whenever problems present pairs of related entities and ask for reachability, distances, or dependencies, graph representations apply.

How the pattern works

First convert edge lists into an adjacency list, mapping each node to an array of its neighbors. Choose your exploration strategy based on the goal: use a queue and breadth-first search to find the shortest path in unweighted networks, or use recursion and depth-first search to explore full paths and detect cycles. Because graphs can have loops, always track visited nodes in a set or boolean array. Add nodes to the visited set at the moment they enter the queue so they are never visited twice.

More Graph problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .