Longest path in a DAG from an edge list
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests graphs, topological sort and dynamic programming.
You are given a directed acyclic graph as a list of edges. Each edge is a pair [u, v] of node names and means there is an edge from u to v. A node exists only if it appears in at least one edge.
Implement:
def longest_path(edges: list[tuple[str, str]]) -> list[str]:
...
Return the nodes of a longest path in the graph, in order from its first node to its last. Path length is the number of edges on it. If several paths share the longest length, return the lexicographically smallest list of node names. If edges is empty, return [].
Constraints
0 <= len(edges) <= 10^4- Node names are 1 to 5 uppercase letters or digits.
- The graph has no cycles. The same edge may appear more than once.
Example 1
edges = [["A","B"], ["B","C"], ["A","C"], ["C","D"]]
output = ["A","B","C","D"]
The edge A -> C is a shortcut; the longest path goes through B and has 3 edges.
Example 2
edges = [["S","M"], ["S","K"], ["M","T"], ["K","T"]]
output = ["S","K","T"]
S -> M -> T and S -> K -> T both have 2 edges. ["S","K","T"] is lexicographically smaller.
Be ready to discuss what should happen if the input does contain a cycle.
Clarifying questions
- Does the lexicographic rule compare node names as strings, so
"10"comes before"9"? - Should duplicate edges be ignored?
- If the input has a cycle, should I raise, or return something?
What a strong answer covers
- Builds an adjacency list without duplicate edges and a topological order with Kahn's algorithm, which also detects a cycle (nodes left unprocessed).
- Computes
longest[v], the most edges on a path starting atv, in reverse topological order: O(V + E). - Picks the smallest-named node with the maximum value, then repeatedly steps to the smallest-named child
cwithlongest[c] = longest[v] - 1; this gives the lexicographically smallest list, because every candidate has the same length. - Returns
[]for no edges, and handles several components and the shortcut edge in Example 1. - Tests both examples, duplicate edges, a single edge, and a graph with a cycle.
Follow-ups
- Weighted edges: the longest path by total weight.
- Count how many longest paths there are.
- Report the cycle when the input has one.
Where it's asked
What it tests
graphs · topological sort · dynamic programming
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
