Medium · Graphs

Detect Cycle

Given a directed graph as adjacency lists adj (adj[u] lists every v with an edge u → v), return true if it contains a directed cycle and false otherwise. The undirected version, where each edge is listed in both endpoints' rows, asks the same about an undirected cycle.

Examples

Example 1

{
  "adj": [
    [1],
    [2],
    [0, 3],
    [4],
    []
  ]
}

Output: cycle: true

Example 2

{
  "adj": [
    [1, 2],
    [3],
    [3],
    [4],
    []
  ]
}

Output: cycle: false

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Graphs problems