Solving Leetcode Interviews in Seconds with AI: Longest Cycle in a Graph
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2360" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge. The graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1. Return the length of the longest cycle in the graph. If no cycle exists, return -1. A cycle is a path that starts and ends at the same node. Example 1: Input: edges = [3,3,4,2,3] Output: 3 Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2. The length of this cycle is 3, so 3 is returned. Example 2: Input: edges = [2,-1,3,1] Output: -1 Explanation: There are no cycles in this graph. Constraints: n == edges.length 2 <= n <= 105 -1 <= edges[i] < n edges[i] != i
Explanation
Here's the breakdown of the approach, complexities, and the Python code:
High-Level Approach:
- Perform a Depth-First Search (DFS) on each unvisited node.
- During DFS, keep track of the path and the distance from the starting node.
- If a cycle is detected (visiting a node already in the current path), calculate the cycle length and update the maximum cycle length found so far.
Complexity:
- Runtime Complexity: O(N)
- Storage Complexity: O(N)
Code
def longestCycle(edges):
n = len(edges)
visited = [False] * n
max_cycle_len = -1
def dfs(node, path, dist):
nonlocal max_cycle_len
visited[node] = True
path[node] = dist
neighbor = edges[node]
if neighbor != -1:
if not visited[neighbor]:
dfs(neighbor, path, dist + 1)
elif neighbor in path:
cycle_len = dist - path[neighbor] + 1
max_cycle_len = max(max_cycle_len, cycle_len)
del path[node] # Backtrack
for i in range(n):
if not visited[i]:
dfs(i, {}, 0)
return max_cycle_len