Skip to content

Program 5 : Unique Elements

Develop a program to check the Uniqueness property of elements in a list and Repeat the experiment for different values of n and plot a graph of the time taken versus n.

Checking Uniqueness

c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 100000

void fillArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        arr[i] = rand() % (2 * n);  
		        // Allows possible duplicates
}

int isUnique(int arr[], int n) {
    int flag = 1;  
    // Assuming all elements are unique
    
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                flag = 0;  // Duplicate found
                return flag;
            }
        }
    }
    return flag;
}

int main() {
    int n;
    printf("Enter size of array (max %d): ", MAX);
    scanf("%d", &n);
    if (n <= 0 || n > MAX) {
        printf("Invalid size.\n");
        return 1;
    }

    int arr[n];
    srand(time(NULL));
    fillArray(arr, n);

    int result = isUnique(arr, n);
    if (result == 1)
        printf("All elements are unique.\n");
    else
        printf("Array contains duplicate elements.\n");

    return 0;
}

Made with ❤️ for students, by a fellow learner.