LeetCode 565: Array Nesting

Problem Description

Explanation

To solve this problem, we can iterate through each element in the array nums. For each element, we can start a cycle and keep traversing the elements until we encounter a duplicate element or reach the original element. By keeping track of the visited elements, we can find the length of the cycle for each element and update the maximum length found so far. The maximum length of a cycle represents the longest length of a set s[k] as required in the problem.

Algorithm:

  1. Initialize a variable maxCount to store the maximum cycle length found so far.
  2. Iterate through each element nums[i] in the array.
  3. Start a cycle from the current element nums[i].
  4. Keep track of the visited elements in the cycle using a boolean array visited.
  5. Traverse the cycle until we encounter a duplicate element or reach the original element nums[i].
  6. Update maxCount with the maximum length of the cycle found.
  7. Return maxCount as the result.

Time Complexity: O(N), where N is the length of the input array nums. Space Complexity: O(N) for the boolean array visited.

Solutions

class Solution {
    public int arrayNesting(int[] nums) {
        int maxCount = 0;
        boolean[] visited = new boolean[nums.length];
        
        for (int i = 0; i < nums.length; i++) {
            int count = 0;
            int j = i;
            while (!visited[j]) {
                visited[j] = true;
                j = nums[j];
                count++;
            }
            maxCount = Math.max(maxCount, count);
        }
        
        return maxCount;
    }
}

Loading editor...