Back to Practice Dashboard
DSA SectionEasy

Cycle Detection

Learn how to solve the 'Cycle Detection' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

Write a function has_cycle(graph) that takes a directed graph represented as an adjacency list of neighbor lists and returns True if it contains at least one cycle, or False otherwise.

Constraints
  • 1 <= V <= 500
  • 0 <= E <= 1000

Examples

Example 1
Input
graph = {0: [1], 1: [2], 2: [0]}
Output
True
Explanation

The path 0 -> 1 -> 2 -> 0 forms a cycle.

Example 2
Input
graph = {0: [1], 1: [2], 2: []}
Output
False
Explanation

The graph is acyclic.

Need a Hint?
Represent graph node connections as an adjacency list/matrix, then use standard BFS or DFS graph traversal.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor