Array Nesting
You are given an integer array nums of length n, where nums is a permutation of the numbers 0 to n - 1. Following the sequence i, numsi, nums[numsi], … eventually returns to i, forming a cycle . Return the length of the longest such cycle across all starting points. Since a permutation splits cleanly into disjoint cycles, walk each unvisited starting index once, following the chain until it loops back, and remember the longest chain found.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ numsi < nums.length
- All the values of nums are unique.
Example
nums = [5, 4, 0, 3, 1, 6, 2]4Explanation Starting at index 0: 0 → 5 → 6 → 2 → back to 0, a cycle of length 4 — the longest one in this array.
In plain terms
- Permutation
- An array containing each number from 0 to n - 1 exactly once, in some order.
- Cycle
- A loop formed by repeatedly jumping from index i to index numsi until you land back where you started.
Walk each unvisited index, following its cycle
Start at index 0. Mark it visited, length becomes 1, jump to nums[0]=5.
What happens in this step
current = 0, length = 1 nums[0] = 5 → current becomes 5
Steps to visualize
- Pick the first index that has not been visited yet and start walking its chain: current, then numscurrent, and so on.
- Mark each index visited as you land on it, counting the length as you go.
- Stop when the chain lands on an already-visited index — that closes the cycle.
- Keep the largest cycle length seen across every starting index, skipping any index already absorbed into an earlier cycle.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Start at index 0. Mark it visited, length becomes 1, jump to nums[0]=5.
What happens in this step
current = 0, length = 1 nums[0] = 5 → current becomes 5
Solution
function arrayNesting(nums) {
const visited = new Array(nums.length).fill(false);
let longest = 0;
for (let i = 0; i < nums.length; i++) {
if (visited[i]) {
continue;
}
let length = 0;
let current = i;
while (!visited[current]) {
visited[current] = true;
current = nums[current];
length++;
}
longest = Math.max(longest, length);
}
return longest;
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [5, 4, 0, 3, 1, 6, 2] | 4 | example from the docstring |
nums = [0] | 1 | smallest valid input: a single self-loop |
nums = [0, 1, 2, 3] | 1 | every index is its own cycle of length 1 |
nums = [3, 2, 1, 0] | 2 | two disjoint cycles of equal length |
nums = [1, 2, 3, 4, 0] | 5 | the entire array forms a single cycle |
nums = [1, 0] | 2 | the smallest non-trivial two-element cycle |