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

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,4,0,3,1,6,2]
Output: 4
💡 Note: Starting from index 0: 0→5→6→2→0 forms a cycle of length 4. This is the longest cycle in the array.
Example 2 — Single Element Cycles
$ Input: nums = [0,1,2]
Output: 1
💡 Note: Each element points to itself: 0→0, 1→1, 2→2. Each forms a cycle of length 1.
Example 3 — Two Cycles
$ Input: nums = [1,2,0,4,3]
Output: 3
💡 Note: Two cycles exist: 0→1→2→0 (length 3) and 3→4→3 (length 2). Maximum is 3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] < nums.length
  • All values in nums are unique

Visualization

Tap to expand
Array Nesting: Finding Longest CycleInput: [5,4,0,3,1,6,2]54031620123456Longest cycle: 0 → 5 → 6 → 2 → 0Length = 4 elementsOutput: 4
Understanding the Visualization
1
Input Array
Array where each value is a valid index
2
Follow Chains
Follow nums[i] → nums[nums[i]] → ... until cycle
3
Find Maximum
Return length of longest cycle found
Key Takeaway
🎯 Key Insight: Each element belongs to exactly one cycle, so mark visited elements globally to avoid redundant work
Asked in
Google 15 Amazon 12 Facebook 8
68.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen