Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Does a directed graph contain a cycle?

Medium · Target 15 minutes · Graphs

A directed graph has n nodes numbered 0 to n − 1, and each pair [u, v] in edges is an edge from u to v. No edge is repeated and none joins a node to itself. Return true if some sequence of edges leads from a node back to itself, and false otherwise.

Examples

InputOutputWhy
n = 6, edges = [[0,1],[0,2],[2,3],[1,3],[3,4],[4,5],[5,3]]true3 → 4 → 5 → 3.
n = 4, edges = [[0,1],[0,2],[1,3],[2,3]]falseTwo routes to 3, but no way back from it.
n = 2, edges = [[0,1],[1,0]]trueTwo opposite edges form a cycle in a directed graph.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ edges.length ≤ 5000
  • No self-loops and no repeated edges

Hints

Hint 1

A visited node is not enough evidence here: the diamond in example 2 reaches 3 twice without a cycle.

Hint 2

Track three states per node: unvisited, on the current path, finished.

Hint 3

An edge into a node that is on the current path closes a cycle. An edge into a finished node never does.

Where people lose marks

  • Reporting a cycle on any visited node, which flags every diamond.
  • Forgetting to colour a node black when its search finishes, so it stays grey and causes false alarms later.
  • Searching only from node 0: a cycle may be unreachable from it.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.