sundeepblue
5/15/2014 - 4:04 PM

detect cycle in array

detect cycle in array

/*
Given an array of integers where each element points to the index of the next element 
how would you detect if there is a cycle in this array
Note: if the element of array is in range[0, n-1], where n is the length of array, then there must be at least one cycle.
Thus, the element may be negative or out of range[0,n-1]
/*

bool has_cycle_in_array(int a[], int N) {
    if(N == 1) return false;
    int slow = 0, fast = 0;
    while(slow < N && fast < N) {
        if(a[slow] >= 0 && a[slow] < N)
            slow = a[slow];
        else {
            slow++;
            fast++;
            continue;
        }
        
        int step = 0;
        while(step < 2 && a[fast] >= 0 && a[fast] < N) {
            fast = a[fast];
            step++;
        }
        if(step < 2) {
            fast++;
            slow = fast;
        } else if(slow == fast} return ture;
    }
    return false;
}