JAVA | Accepted | O(n) | constant space |


  • 0
    S

    Idea - is to calculate the direction initially. Traverse the each element in the array if direction matches then continue or else return false. Every time we visit the array , we set it as 0. if we get 0 again in future while traverse that mean it's a loop terminate and return false.

    public class Solution {

    public boolean circularArrayLoop(int[] nums) {
        int index =0;
        if(nums.length == 0) return false;
    
        boolean directionForward = (nums[index] >=0 ) ? true : false;
        while(true){
           
            if(index < 0 ) return false;
            if(index >= nums.length) index = index % (nums.length);
            
            // if new direction following current direcntion
            if(directionForward != ((nums[index] >=0 ) ? true : false)) return false;
            if(nums[index] == 0) return true;
            int temp = nums[index];
            nums[index] = 0;
            index += temp;
        }   
    }
    

    }


Log in to reply
 

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