Back to course home
0% completed
Vote For New Content
Better solution
Ankit Joshi
Apr 20, 2025
Floyd's algorithm will eventually find any cycle that exists, even if we start from index 0
class Solution { public boolean loopExists(int[] arr) { int slow = 0; int fast = 0; do{ slow = getNext(arr, slow); fast = getNext(arr, getNext(arr, fast)); }while(slow!=fast); int length = getCycleLength(arr,slow) ; return length>1; } int getNext(int a[], int index){ int val = a[index]+a.length+index; return val%a.length; } int getCycleLength(int a[], int slow){ int index = slow; boolean isNegative = false; boolean isPositive = false; int count = 0; if(a[slow]>0){ isPositive = true; }else{ isNegative = true; } do{ index = getNext(a, index); if(a[index]>0){ isPositive = true; }else{ isNegative = true; } count++; }while(index!=slow); if(isNegative && isPositive){ return 0; } return count ; } }
0
0
Comments
Comments
Ankit Joshi6 months ago
Update - Not correct it will fail for this test case
[1,-1,2,2,2,2,2,4]
On this page