Skip to content

565. Array Nesting 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int arrayNesting(vector<int>& nums) {
    int ans = 0;

    for (const int num : nums) {
      if (num == -1)
        continue;
      int index = num;
      int count = 0;
      while (nums[index] != -1) {
        const int cache = index;
        index = nums[index];
        nums[cache] = -1;
        ++count;
      }
      ans = max(ans, count);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int arrayNesting(int[] nums) {
    int ans = 0;

    for (final int num : nums) {
      if (num == -1)
        continue;
      int index = num;
      int count = 0;
      while (nums[index] != -1) {
        final int cache = index;
        index = nums[index];
        nums[cache] = -1;
        ++count;
      }
      ans = Math.max(ans, count);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def arrayNesting(self, nums: list[int]) -> int:
    ans = 0

    for num in nums:
      if num == -1:
        continue
      index = num
      count = 0
      while nums[index] != -1:
        cache = index
        index = nums[index]
        nums[cache] = -1
        count += 1
      ans = max(ans, count)

    return ans