Skip to main content
LeetCode 565, Medium. Topics: Array, Depth-First Search. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

Problem

You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1]. You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
  • The first element in s[k] starts with the selection of the element nums[k] of index = k.
  • The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
  • We stop adding right before a duplicate element occurs in s[k].
Return the longest length of a set s[k].

Examples

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] < nums.length
  • All the values of nums are unique.
Follow-up: Could you solve it using constant extra space complexity?

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026