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 - DFS with Global Visited Array INPUT nums = [5,4,0,3,1,6,2] Index: 0 1 2 3 4 5 6 5 4 0 3 1 6 2 Cycle Structure: 0 5 6 2 Cycle 1: length = 4 1 4 Cycle 2: len=2 3 Cycle 3: len=1 ALGORITHM STEPS 1 Initialize Create visited[] array maxLen = 0 2 DFS from each index For i=0 to n-1: if not visited[i] start DFS traversal 3 Follow chain curr = i, count = 0 while not visited[curr]: mark visited, count++ curr = nums[curr] 4 Update max maxLen = max(maxLen, count) Continue to next unvisited Example: i=0 0-->5-->6-->2-->0 (stop) count = 4 FINAL RESULT Cycles Found: Cycle 1: 0-5-6-2 Length: 4 Cycle 2: 1-4 Len: 2 Cycle 3: 3 Len: 1 Maximum Length: max(4, 2, 1) = 4 Output 4 OK - Longest set s[0] = {5, 6, 2, 0} visited[] final: [T,T,T,T,T,T,T] All elements visited Key Insight: Since nums is a permutation of [0, n-1], following indices creates disjoint cycles. Using a global visited array ensures each element is processed exactly once --> O(n) time. No need to revisit elements in already-found cycles as they will produce the same set. TutorialsPoint - Array Nesting | DFS with Global Visited Array Time: O(n) | Space: O(n)
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