Array Nesting Problem
Description
LeetCode Problem 565.
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].
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^5
- 0 <= nums[i] < nums.length
- All the values of nums are unique.
Solution
Approach: Walk Each Cycle Once
Since nums is a permutation of 0..n-1, following i -> nums[i] from any index never stops at a dead end and never merges into another path: every value is the target of exactly one index. So the indices split into separate cycles, and s[k] is exactly the cycle that contains k. The answer is the length of the longest cycle.
Building s[k] separately for every k takes O(n2) time when there is one big cycle. But every index on a cycle gives a set of the same size, so each cycle only needs to be walked once:
- Keep a
visitedflag for every index. - For each
start, followi = nums[i]fromstart, marking each index and counting steps, until reaching an index that is already visited. - Keep the largest count.
When start is new, the walk goes around its whole cycle and stops when it comes back to start, so the count is the cycle's length. When start already belongs to a walked cycle, the loop stops immediately with a count of 0. In Example 1, the walk from index 0 visits 0 → 5 → 6 → 2 and returns to 0, length 4; the walks from 5, 6 and 2 then count 0.
We could mark visits by overwriting nums instead of using a separate array, which saves the extra space but changes the input.
Complexity: O(n) time, where n is the length of nums, since each index is marked once, and O(n) space for visited.
class Solution:
def arrayNesting(self, nums: List[int]) -> int:
visited = [False] * len(nums)
longest = 0
for start in range(len(nums)):
# Walk the cycle that contains start, unless an earlier walk already covered it.
length = 0
i = start
while not visited[i]:
visited[i] = True
i = nums[i]
length += 1
longest = max(longest, length)
return longest