As reported: Cohesity Software Engineer (2–5 years), India, March 2026, round 1 (DSA): cycle detection in a directed graph. The interviewer asked for the optimal complexity before a first implementation.
You are given a directed graph with n nodes labeled 0 to n - 1 and a list edges, where edges[i] = [u, v] is a directed edge from u to v. Return true if the graph contains a directed cycle, otherwise false.
This is the same check as LeetCode 207 — Course Schedule (our write-up: /course-schedule), which returns the opposite: whether all courses can be finished, i.e. whether the prerequisite graph has no cycle.
Example 1
n = 4, edges = [[0,1],[1,2],[2,3]]
Output: false
Example 2
n = 4, edges = [[0,1],[1,2],[2,0],[2,3]]
Output: true
0 → 1 → 2 → 0 is a cycle.
Example 3
n = 3, edges = [[0,1],[0,2],[1,2]]
Output: false
Two paths lead from 0 to 2, but no path returns to where it started: undirected cycles do not count.
Constraints: 1 <= n <= 10^5, 0 <= edges.length <= 2 * 10^5, 0 <= u, v < n. Self-loops (u == v) count as cycles; duplicate edges may appear. The graph may be disconnected.
Code runner format: one JSON value per line: n, edges. Implement hasCycle(n, edges) returning true or false.