565: Time 90.23%, Solution with step by step explanation
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nInitialize a boolean visited list of size n, where visited[i] indicates i
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInitialize a boolean visited list of size n, where visited[i] indicates if nums[i] has been visited or not.\nInitialize a variable max_length to zero, which will be used to store the maximum length of any set.\nIterate over all elements of nums using a for loop with loop variable i:\nCheck if nums[i] has already been visited, by checking if visited[i] is True. If it has been visited, skip to the next iteration of the loop.\nIf nums[i] has not been visited, initialize a variable length to zero.\nSet a variable j to i, which is the starting index of the current set.\nEnter a while loop that runs until nums[j] has already been visited:\nMark nums[j] as visited by setting visited[j] to True.\nSet j to nums[j], which is the index of the next element in the current set.\nIncrement length by one.\nIf the length of the current set is greater than max_length, update max_length to the length of the current set.\nReturn max_length.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n    def arrayNesting(self, nums: List[int]) -> int:\n        visited = [False] * len(nums)  # mark if a number is visited\n        max_length = 0\n        \n        for i in range(len(nums)):\n            if visited[i]:  # if already visited, skip\n                continue\n                \n            length = 0\n            j = i\n            while not visited[j]:\n                visited[j] = True  # mark as visited\n                j = nums[j]  # move to next element in set\n                length += 1\n                \n            max_length = max(max_length, length)  # update max_length\n            \n        return max_length\n\n```
['Array', 'Depth-First Search', 'Python', 'Python3']