[JAVA] Check cyclic - O(n) time & O(1) space
The problem we can think about both unique and non-unique.\nIf elements is unique in array we can just simply modify the array to check if we already visited or
The problem we can think about both unique and non-unique.\nIf elements is unique in array we can just simply modify the array to check if we already visited or not.\n```\n    public int arrayNesting(int[] nums) {\n        int result = 0;\n        for(int i = 0; i< nums.length; i++) {\n            result = Math.max(result, dfs(nums, i));\n        }\n        \n        return result;\n    }\n    \n    private int dfs(int[] nums, int currentIndex) {\n        if(nums[currentIndex] < 0) return 0;\n        int nextIndex = nums[currentIndex];\n        nums[currentIndex] = -1;\n        return dfs(nums, nextIndex) + 1;\n    }\n```\n\nIn non-unique case we can use another array to record the step we already visited last time.\n```\n    public int arrayNesting(int[] nums) {\n        \n        int[] dp = new int[nums.length];\n        \n        int result = 0;\n        for(int i = 0; i < nums.length; i++) {\n            result = Math.max(result, dfs(nums, i, dp));\n        }\n        \n        return result;\n    }\n    \n    private int dfs(int[] nums, int currentIndex, int[] dp) {\n        if(dp[currentIndex] < 0) return 0;\n        \n        if(dp[currentIndex] > 0) return dp[currentIndex];\n        \n        dp[currentIndex] = -1;\n        int result = 1 + dfs(nums, nums[currentIndex], dp);\n        dp[currentIndex] = result;\n        \n        return result;\n    }\n```
[]