LeetCode Solutions

565. Array Nesting

Time: $O(n)$

Space: $O(1)$

			

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) {  // Not yet seen
        const int cache = index;
        index = nums[index];  // Get next index
        nums[cache] = -1;     // Already seen
        ++count;
      }
      ans = max(ans, count);
    }

    return ans;
  }
};
			

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) { // Not yet seen
        final int cache = index;
        index = nums[index]; // Get next index
        nums[cache] = -1;    // Already seen
        ++count;
      }
      ans = Math.max(ans, count);
    }

    return ans;
  }
}
			

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:
        temp = index
        index = nums[index]
        nums[temp] = -1
        count += 1
      ans = max(ans, count)

    return ans