DSA SectionEasy

Cycle Detection

Detailed guide and Python implementation for the 'Cycle Detection' problem.

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?
Consider using Graphs-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.