Array Nesting
MediumUpdated: Aug 2, 2025
Practice on:
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 elementnums[k]ofindex = k. - The next element in
s[k]should benums[nums[k]], and thennums[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
Example 1
Input: nums = [5,4,0,3,1,6,2]
Output: 4
Explanation:
nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
One of the longest sets s[k]:
s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
Example 2
Input: nums = [0,1,2]
Output: 1
Constraints
1 <= nums.length <= 10^50 <= nums[i] < nums.length- All the values of
numsare unique.
Solution
Method 1 – Cycle Detection with Visited Marking
Intuition
The problem is about finding the largest cycle in a permutation array. Since each number is unique and in the range [0, n-1], following the chain from any index will eventually loop back, forming a cycle. By marking visited elements, we avoid redundant work and ensure each cycle is counted only once.
Approach
- Initialize a boolean array
visitedof sizento track visited indices. - For each index
iinnums:
- If
iis not visited:- Start traversing from
i, following the chainnums[i] -> nums[nums[i]] -> .... - For each step, mark the current index as visited and increment a counter.
- Stop when you reach an already visited index (cycle detected).
- Update the answer if the current cycle length is greater.
- Start traversing from
- Return the maximum cycle length found.
Code
C++
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int n = nums.size(), ans = 0;
vector<bool> vis(n, false);
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
int cnt = 0, j = i;
while (!vis[j]) {
vis[j] = true;
j = nums[j];
++cnt;
}
ans = max(ans, cnt);
}
}
return ans;
}
};
Java
class Solution {
public int arrayNesting(int[] nums) {
int n = nums.length, ans = 0;
boolean[] vis = new boolean[n];
for (int i = 0; i < n; ++i) {
if (!vis[i]) {
int cnt = 0, j = i;
while (!vis[j]) {
vis[j] = true;
j = nums[j];
cnt++;
}
ans = Math.max(ans, cnt);
}
}
return ans;
}
}
Python
class Solution:
def arrayNesting(self, nums: list[int]) -> int:
n: int = len(nums)
vis: list[bool] = [False] * n
ans: int = 0
for i in range(n):
if not vis[i]:
cnt: int = 0
j: int = i
while not vis[j]:
vis[j] = True
j = nums[j]
cnt += 1
ans = max(ans, cnt)
return ans
Complexity
- ⏰ Time complexity:
O(n)— Each index is visited at most once. - 🧺 Space complexity:
O(n)— For the visited array.