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

Longest Weighted Path in a DAG

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)

Examples

Example 1

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.

query.sql