Java O(n) time with O(n) Space


  • 0
    A
    public int arrayNesting(int[] nums) {
            Set<Integer> alreadyVisited = new HashSet<Integer>();
            int maxSize = 0;
            for(int i = 0; i < nums.length; i++) {
                int j = nums[i];
                if(alreadyVisited.contains(j)){
                    continue;
                }else {
                    alreadyVisited.add(j);
                }
                int size = 1;
                while(nums[j] != nums[i]) {
                    j = nums[j];
                    if(alreadyVisited.contains(j)){
                        break;
                    }else {
                        alreadyVisited.add(j);
                    }
                    size++;
                }
                if(size > maxSize) {
                    maxSize = size;
                }
                if(maxSize == nums.length) {
                    break;
                }
            }
            return maxSize;
        }
    

    For O(1) space refer @compton_scatter's solution here. Modifying the source array to avoid extra space is a perfect solution.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.