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:
s[k]
starts with the selection of the element nums[k]
of nums
.s[k]
is nums[nums[k]]
, and then nums[nums[nums[k]]]
, and so on.a set is formed
, meaning the next value to pick already exists in the set.Return the size of the largest set s[k]
formed.
Before solving the problem, let’s clarify a few things:
nums
array guaranteed to be a permutation of [0, n-1]
?
[0, n-1]
forms a valid cycle.To solve this, we’ll employ the following strategy:
def arrayNesting(nums):
visited = [False] * len(nums) # To keep track of visited elements
max_size = 0 # To keep track of the maximum set size
for i in range(len(nums)):
if not visited[i]:
start = nums[i]
count = 0
while not visited[start]:
visited[start] = True
start = nums[start]
count += 1
max_size = max(max_size, count)
return max_size
visited
array takes up linear space relative to the input size.This approach ensures that we efficiently find the maximum set size while keeping track of visited elements to avoid redundant calculations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?