Find Duplicate in Range 0 and n-1

Code

#include <stdio.h>
#include <stdint.h>

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

    int res = -1;

    uint8_t i = 0;
    for ( ; i < (n - 1) ; i++)
    {
        uint8_t j = i + 1;
        for ( ; j < n; j++)
        {
            if (arr[i] == arr[j])
            {
                res = arr[i];
                break;
            }
            else
            {

            }
        }
    }
    
    return res;
}

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

his C program identifies a duplicate value within an array of integers. It uses a nested loop strategy to compare each element against every other element in the list.

How the Logic Works

The function find_duplicate uses a "brute-force" comparison method.

  1. Safety Check: It first checks if the array pointer is NULL to prevent a system crash.
  2. Outer Loop (i): This loop picks an element one by one, starting from the first position.
  3. Inner Loop (j): This loop starts from the element immediately after i and scans the rest of the array to see if any value matches arr[i].
  4. The Match: If a match is found (arr[i] == arr[j]), the value is stored in res.
  5. Return: If a duplicate is found, it returns that value. If no duplicates exist after checking all pairs, it returns -1.
Upvote
Downvote
Loading...

Input

5 0 1 2 3 2

Expected Output

2