Find Duplicate in Range 0 and n-1

Code

#include <stdio.h>

int find_duplicate(int arr[], int n) {
    if (n <= 1) {
        return -1;
    }

    int slow = arr[n - 1];
    int fast = arr[n - 1];

    // Phase 1: Detect cycle
    do {
        slow = arr[slow];
        fast = arr[arr[fast]];
    } while (slow != fast);

    // Phase 2: Find entry point of cycle
    slow = arr[n - 1];
    while (slow != fast) {
        slow = arr[slow];
        fast = arr[fast];
    }

    return slow;
}


int main() {
    int n;
    scanf("%d", &n);

    // Assuming the array size is at most 100 for this example
    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int result = find_duplicate(arr, n);
    printf("%d\n", result);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 0 1 2 3 2

Expected Output

2