Detect Cycle in a Directed Graph using DFS

🚀 Day 9/100 — 💻 Problem: Detect Cycle in a Directed Graph Given a graph, check if it contains a cycle Concept: DFS + Recursion Stack — Traverse each node using DFS — Track visited nodes — Maintain a recursion stack — If a node is visited again in the same path → cycle detected def has_cycle(graph): visited = set() rec_stack = set() def dfs(node): if node in rec_stack: return True if node in visited: return False visited.add(node) rec_stack.add(node) for neighbor in graph[node]: if dfs(neighbor): return True rec_stack.remove(node) return False for node in graph: if dfs(node): return True return False What I learned: Not all problems are about values… some are about relationships. Tracking the path is as important as visiting nodes Time Complexity: O(V + E) Graph problems are all about how things are connected! #100DaysOfCode #DSA #Graphs #DFS #CodingInterview #ProblemSolving #PlacementPrep

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories