Program to check whether odd length cycle is in a graph or not in Python

In graph theory, an odd-length cycle is a cycle that contains an odd number of vertices. To detect such cycles in an undirected graph, we can use Depth-First Search (DFS) with path tracking to identify back edges that form odd cycles.

Problem Understanding

Given an undirected graph represented as an adjacency list, we need to determine if there exists any cycle with an odd number of vertices. For example, cycles like [1, 3, 4] (length 3) or [0, 1, 3, 4, 2] (length 5) are odd-length cycles.

0 1 2 3 4

Algorithm Approach

The solution uses DFS with path tracking to detect cycles. When we encounter a back edge (an edge to a vertex already in the current path), we check if the cycle length is odd by calculating the difference in depths.

Implementation

class Solution:
    def solve(self, adj_list):
        def dfs(node, depth):
            if node in path:
                return (depth - path[node]) % 2 == 1
            if node in visited:
                return False
            
            visited.add(node)
            path[node] = depth
            
            for neighbor in adj_list[node]:
                if dfs(neighbor, depth + 1):
                    return True
            
            del path[node]
            return False
        
        visited, path = set(), {}
        
        for i in range(len(adj_list)):
            if dfs(i, 0):
                return True
        
        return False

# Test the solution
solution = Solution()
adj_list = [[1, 2], [0, 3, 4], [0, 3, 4], [1, 2, 4], [1, 2, 3]]
result = solution.solve(adj_list)
print(f"Has odd-length cycle: {result}")
Has odd-length cycle: True

How It Works

The algorithm tracks two key data structures:

  • visited: Set of nodes that have been completely processed
  • path: Dictionary mapping current path nodes to their depths

When we find a back edge to a node in the current path, we calculate (current_depth - path_depth) % 2. If this equals 1, we've found an odd-length cycle.

Example Walkthrough

# Let's trace through a simple example
adj_list = [[1], [0, 2], [1, 3], [2]]  # Simple path: 0-1-2-3

solution = Solution()
result = solution.solve(adj_list)
print(f"Simple path has odd cycle: {result}")

# Triangle graph (odd cycle of length 3)
triangle = [[1, 2], [0, 2], [0, 1]]
result = solution.solve(triangle)
print(f"Triangle has odd cycle: {result}")
Simple path has odd cycle: False
Triangle has odd cycle: True

Time and Space Complexity

Complexity Value Explanation
Time O(V + E) Visit each vertex and edge once
Space O(V) Recursion stack and tracking sets

Conclusion

This DFS-based solution efficiently detects odd-length cycles by tracking path depths and checking cycle parity when back edges are found. The algorithm works in linear time and is particularly useful in bipartite graph testing, since a graph is bipartite if and only if it contains no odd-length cycles.

Updated on: 2026-03-25T13:27:55+05:30

524 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements