Detect a Cycle in a Directed Graph
Updated
Problem statement
Given n vertices numbered 0 through n - 1 and directed edges [u, v] from u to v, return whether the graph contains any directed cycle.
The graph may be disconnected. A self-loop counts as a cycle. Parallel edges are allowed and do not by themselves form a cycle.
Function
hasDirectedCycle(n: int, edges: int[][]) → booleanExamples
Example 1
n = 3edges = [[0,1],[1,2],[2,0]]return = trueThe edges form the directed cycle 0 to 1 to 2 to 0.
Example 2
n = 4edges = [[0,1],[0,2],[1,3],[2,3]]return = falseBoth paths merge at node 3, but no edge leads back to an ancestor.
Example 3
n = 3edges = [[2,2]]return = trueA self-loop is a directed cycle even in a disconnected component.
Constraints
0 <= n <= 100000.0 <= edges.length <= 200000.- Each edge has two valid vertex indices; when
n == 0, the edge array is empty.
More Oracle Phone Screen questions
- Remove Parentheses from a Plus-Minus ExpressionPHONE SCREEN · Seen Nov 2026
- Trapping Rain WaterPHONE SCREEN · Seen Oct 2026
- Shortest Window by Distinct-Value SumPHONE SCREEN · Seen Oct 2026
- Time-Based Key-Value StorePHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Remove Adjacent Duplicates in String IIPHONE SCREEN · Seen Oct 2026
- Sum Root-to-Leaf Binary NumbersPHONE SCREEN · Seen Oct 2026
- Longest All-Present Attendance StreakPHONE SCREEN · Seen Oct 2026
- Next PermutationPHONE SCREEN · Seen Sep 2026
- Valid ParenthesesPHONE SCREEN · Seen Sep 2026
- Valid Parenthesis StringPHONE SCREEN · Seen Sep 2026
Similar questions at other companies
- Merge Event PreferencesAirbnb · PHONE SCREEN · ONSITE INTERVIEWAirbnb interview questions
- Course ScheduleAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Network Layer Execution OrderNVIDIA · PHONE SCREENNVIDIA interview questions
- Task Build Order and File-Change RerunsVanta · PHONE SCREEN
- Task Scheduler with Prerequisites and Execution PathsBrex · PHONE SCREEN
- All Halfway Courses Across Course TracksCrunchyroll · PHONE SCREENCrunchyroll interview questions
- Course Schedule Cycle DetectionGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Dependency-Aware Task SchedulerRippling · PHONE SCREENRippling interview questions
- Lexicographically Smallest Topological OrderByteDance · PHONE SCREEN · ONSITE INTERVIEWByteDance interview questions
- Build Packages as Dependencies Are DiscoveredMongoDB · PHONE SCREENMongoDB interview questions