C# - fast and slow pointer solution to find loop


  • 0
        public bool CircularArrayLoop(int[] nums) 
        {
            if (nums.Length < 2) return false;
            
            int indexSlow = 0;
            int indexFast = 0;
            int count = 0;
            int steps = 0;
            int len = nums.Length;
            bool forward = nums[0] > 0;
            
            do
            {
                if ((forward && (nums[indexSlow] < 0 || nums[indexFast] < 0))
                        || (!forward && (nums[indexSlow] > 0 || nums[indexFast] > 0)))
                {
                    return false;
                }
                
                steps += Math.Abs(nums[indexSlow]);
                indexSlow = Mod(Next(nums, indexSlow), len);
                indexFast = Mod(Next(nums, indexFast), len);
                indexFast = Mod(Next(nums, indexFast), len);
                count++;
            }
            while (count < nums.Length && indexSlow != indexFast);
            
            return indexSlow == indexFast && steps > 1;
        }
        
        public int Next(int[] nums, int index)
        {
            int len = nums.Length;
            int forward = nums[index];
            return Mod(index + forward, len);
        }
        
        public int Mod(int val, int len)
        {
            return ((val % len) + len) % len;
        }
    

Log in to reply
 

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