JAVA SOLUTION USING HASHSET
The main idea is to check for every index and keep count of the distinct elements which is donw by using HashSet.\n\nclass Solution {\n    public int arrayNesti
The main idea is to check for every index and keep count of the distinct elements which is donw by using HashSet.\n```\nclass Solution {\n    public int arrayNesting(int[] nums) {\n        int n = nums.length;\n        int ans = Integer.MIN_VALUE;\n        for(int i = 0 ; i < n ; i++){\n            HashSet<Integer> hs = new HashSet<>();\n            hs.add(nums[i]);\n            int x = nums[i];\n            while(!hs.contains(nums[x])){\n                hs.add(nums[x]);\n                x = nums[x];\n            }\n            ans = Math.max(ans , hs.size());\n        }\n        return ans;\n    }\n}\n```\nResult: TLE in last 3 test cases.\n\nObservation: We can use a single HashSet for the entire operation. Since there are elements from 0 to (n - 1) so overlapping indexes can be avoided by keeping track of the number of times insertion is done. The implementation is given below.\n\n```\nclass Solution {\n    public int arrayNesting(int[] nums) {\n        int n = nums.length;\n        HashSet<Integer> hs = new HashSet<>();\n        int ans = Integer.MIN_VALUE;\n        for(int i = 0 ; i < n ; i++){\n            int j = i;\n            int count = 0;\n            while(!hs.contains(nums[j])){\n                hs.add(nums[j]);\n                j = nums[j];\n                count++;\n            }\n            ans = Math.max(ans , count);\n        }\n        return ans;\n    }\n}\n```\nResult : Accepted. \nDo upvote id it was helpful.
['Java']