Find Duplicate in Range 0 and n-1

Code

#include <stdio.h>

int find_duplicate(int arr[], int n) {
    // search all numbers
    for (int i = 0; i < n; i++) {
        int found = 0;
        for (int pos = 0; pos < n; pos++) {
            if (arr[pos] == i) {
                if (found) {
                    // second time finding the number
                    return i;
                } else {
                    // first time finding the number
                    found = 1;
                }
            }
        }
    }
    return -1;
}

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

    int arr[100];
    for (int i = 0; i < n; i++) scanf("%d", &arr[i]);

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 0 1 2 3 2

Expected Output

2