KatInterview

Does This One-Way Network Contain a Loop?

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsgraphdirected-graphcycle-detection

Last updated

Decide whether a directed graph given as an adjacency list contains a cycle, handling self-loops, parallel edges, disconnected parts and an empty graph.

Does This One-Way Network Contain a Loop?

You are given a network of one-way links between nodes. The network is stored as an adjacency list called adj. Nodes are numbered 0 to n - 1, where n = len(adj), and adj[u] lists every node v that has a one-way link u -> v.

Return True if you can start at some node, follow links, and come back to the node you started from (a directed cycle). Return False otherwise.

Rules and edge cases

  • The graph may be disconnected. A cycle in any part of it counts.
  • A self-loop (u appears in adj[u]) is a cycle.
  • The same link may be listed more than once in adj[u]. Repeated links alone do not form a cycle; only a genuine route that returns to its start does.
  • Two links in opposite directions between the same pair of nodes (u -> v and v -> u) form a cycle.
  • Nodes reachable by several different routes do not by themselves imply a cycle. Only a route that returns to its start does.
  • If adj is empty (no nodes), return False.

Input

  • adj: a list of lists of integers. adj[u] holds the targets of the links leaving node u. Every value is a valid node index in [0, n - 1].

Output

  • A boolean: True if the graph contains a directed cycle, otherwise False.

Constraints

  • 0 <= n <= 10^5
  • 0 <= m <= 2 * 10^5, where m is the total number of entries across all lists
  • 0 <= adj[u][i] < n
  • Aim for O(n + m) time.

Examples

Example 1

Input: contains_cycle([[1], [2], [0]])

Output: True

Example 2

Input: contains_cycle([[1], [2], []])

Output: False

Example 3

Input: contains_cycle([[1, 2], [2], []])

Output: False

Example 4

Input: contains_cycle([[], [0], []])

Output: False

Hints

Hint 1

A visited set is not enough for directed graphs: a node can be reached by two different routes without any cycle. You need to tell apart 'on my current path' from 'seen earlier'.

Hint 2

Try repeatedly removing nodes that have no incoming links. What does it mean if some nodes can never be removed?

Hint 3

Count incoming links per node (counting repeats separately), start from nodes with count 0, and decrement counts of targets as you remove nodes. Compare how many nodes were removed to n.