#565

Array Nesting

Medium
ArrayDepth-First SearchHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach leverages the fact that each index can only be part of one set. By marking visited indices, we can efficiently calculate the length of each set without revisiting elements.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a visited array to keep track of indices that have been processed.
  2. 2Step 2: For each index, if it hasn't been visited, start a new set and follow the sequence until a duplicate is found.
  3. 3Step 3: Update the maximum length based on the length of the current set.
solution.py13 lines
1def arrayNesting(nums):
2    visited = [False] * len(nums)
3    max_length = 0
4    for i in range(len(nums)):
5        if not visited[i]:
6            current_length = 0
7            current_index = i
8            while not visited[current_index]:
9                visited[current_index] = True
10                current_index = nums[current_index]
11                current_length += 1
12            max_length = max(max_length, current_length)
13    return max_length

Complexity note: The time complexity is O(n) because each index is processed only once, leading to linear time. The space complexity is O(n) due to the visited array that tracks which indices have been processed.

  • 1Each index can only be part of one unique set due to the permutation property.
  • 2Tracking visited indices allows for efficient computation of set lengths.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.