Interview Questions/SQL/Longest Weighted Path in a DAG

Longest Weighted Path in a DAG

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a directed acyclic graph (DAG) with weighted edges. Using a recursive CTE, enumerate all paths from every possible starting node and find the globally longest path by total edge weight. Return all paths that share the maximum total weight. Return (start_node, end_node, total_weight, path) ordered by start_node, then path. Table: Nodes

Column NameTypeDescription
node_idINTPrimary key
node_nameVARCHARNode label

Table: Edges

Column NameTypeDescription
from_nodeINTSource node
to_nodeINTDestination node
weightINTEdge weight (non-negative)

Database Schema (Inferred)

Nodes

Column NameExample Value
node_id1
node_nameA

Edges

Column NameExample Value
from_node1
to_node2
weight4

Example

Nodes

node_idnode_name
1A
2B
3C
4D
5E
6F

Edges

from_nodeto_nodeweight
124
132
245
253
356
462
564

Output

start_nodeend_nodetotal_weightpath
16121->3->5->6

Explanation:

All paths from node 1: 1→2→4→6 (weight 11), 1→2→5→6 (weight 11), 1→3→5→6 (weight 12). The path through node 3 is longest at weight 12. The visited guard prevents cycles. Only globally maximum-weight paths are returned.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Nodes

node_idnode_name
1A
2B
3C
4D
5E
6F

Edges

from_nodeto_nodeweight
124
132
245
253
356
462
564

Output

start_nodeend_nodetotal_weightpath
16121->3->5->6