Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2360: Longest Cycle in a Graph

In this guide, we solve Leetcode #2360 Longest Cycle in a Graph in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

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].

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Graph, Topological Sort

Intuition

The data forms a graph, so we should explore nodes and edges systematically.

A traversal ensures we visit each node once while maintaining the needed state.

Approach

Build an adjacency list and traverse with BFS or DFS.

Aggregate results as you visit nodes.

Steps:

  • Build the graph.
  • Traverse with BFS/DFS.
  • Accumulate the required output.

Example

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.

Python Solution

class Solution: def longestCycle(self, edges: List[int]) -> int: n = len(edges) vis = [False] * n ans = -1 for i in range(n): if vis[i]: continue j = i cycle = [] while j != -1 and not vis[j]: vis[j] = True cycle.append(j) j = edges[j] if j == -1: continue m = len(cycle) k = next((k for k in range(m) if cycle[k] == j), inf) ans = max(ans, m - k) return ans

Complexity

The time complexity is O(n)O(n)O(n) and the space complexity is O(n)O(n)O(n), where nnn is the number of nodes. The space complexity is O(n)O(n)O(n), where nnn is the number of nodes.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy