Find Duplicate in Range 0 and n-1

Code

#include <stdio.h>

int find_duplicate(int arr[], int n) {
    // Your logic here
    int temp = 0, count = 0;
    for(int i = 0; i < n - 1; i++)      //(O(2*n))
    {
        temp = arr[count] ^ arr[i + 1]; //xor with next element 
        if(temp == 0)                   //if same then 0, return the matched duplicate
        {
            return arr[count];
        }
        else if((i + 1) == (n-1))       //If match not found push the head to next element and reiterate from it
        {
            count++;
            i = count;
        }
        else if(count == (n-1)) // If max reached then exit, no match!
        {
            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