Skip to content
Problem 565 · LeetCode 565(opens in a new tab)

Array Nesting

MediumArrays

You are given an array nums of length n that holds each number from 0 to n − 1 exactly once, in some order.

Pick a start index k and keep jumping: read nums[k], treat it as the next index, read the value there, and so on. Collect the values you read, and stop just before a value would be collected a second time. Return the size of the largest collection any start index can produce.

Example 1

Input:  nums = [1, 2, 0, 4, 3]
Output: 3
Why:    from 0 you read 1, 2, 0, then 1 again: {1, 2, 0}
2 more examples and the constraints

Example 2

Input:  nums = [0, 1, 2, 3]
Output: 1
Why:    every index points to itself

Example 3

Input:  nums = [2, 0, 4, 1, 3, 6, 5]
Output: 5
Why:    0 → 2 → 4 → 3 → 1 → 0 visits five values

Constraints

  • 1 ≤ n ≤ 100,000
  • 0 ≤ nums[i] < n
  • All values in nums are different

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Walk from every startO(n²)
  2. Measure each cycle onceO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work, one cycle of 100,000 indexesVerdict
Walk from every startO(n²)
Walks each cycle once per member
Measure each cycle onceO(n)
Best; every index marked once

n = length of nums.

Edge cases to test

  • Fixed points. nums[i] = i is a cycle of length 1, so the answer is at least 1.
  • One big cycle. The whole array is one loop: the answer is n, and the naive method does n² steps.
  • One element. [0] gives 1.
  • Using −1 as the mark. It is safe because real values are 0 to n − 1, but the input is changed; copy it or use a visited array if that matters.

Common mistakes

  • Marking a slot before saving its value, so the walk loses the next index.
  • Resetting marks for each new start, which brings back the O(n²) cost.
  • Counting one extra step by including the repeated value at the end.

How to talk through it

  1. 1Clarify. Is nums always a permutation of 0..n − 1? May I change the input?
  2. 2Name the structure. One arrow out and one arrow in per index means the indexes form disjoint cycles; each set is one cycle.
  3. 3Give the naive walk. Walk from every start: O(n²) when the cycle is long.
  4. 4Measure each cycle once. Mark indexes as you leave them and skip marked starts: O(n) time, O(1) extra space.
  5. 5Test out loud. Run [1, 2, 0, 4, 3] and the all-fixed-points array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?