Simple O(1) space and O(n) time complexity solution


  • 0
    D

    public class Solution {
    public boolean circularArrayLoop(int[] nums) {

        //Base case: if less than 2 elements are present return false
        if(nums.length<2)
            return false;
            
        //General case: if 2 or more elements are present
        
        
        //index to keep track of current position
        int i=0;
        //to keep track of visited index
        int temp;
        
        //variable to see if loooped through array
        boolean traverseFull=false;
        
        while(true)
        {
            //if gone beyond bounds of array, set variable to true
            if((i+nums[i])>=nums.length ||(i+nums[i])<0)
                traverseFull=true;
        
            temp=i;
            i=Math.floorMod(i+nums[i], nums.length);
            
            //set value of visited index to 0
            nums[temp]=0;
            
            //if index is visited, break out of loop
            if(nums[i]==0)
            {
                break;
            }
            else
            {
            	continue;
            }
        }
        
        //if reached start index and looped through array, return true
        if(i==0 && traverseFull)
        	return true;
        else
        	return false;
        
    }
        
    }

Log in to reply
 

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