How to check whether an array contains any unique values in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

bool containsUniqueValues(int arr[], int size) {
    // Create an array to count frequencies of values
    int frequency[1024] = {0}; // Assuming numbers are within the range of 0 to 2013

    // Count occurrences of each number
    for (int i = 0; i < size; i++) {
        frequency[arr[i]]++;
    }

    // Check if any number appears only once
    for (int i = 0; i < size; i++) {
        if (frequency[arr[i]] == 1) {
            return true; // Found a unique value
        }
    }

    return false; // No unique value found
}

int main() {
    int arr[] = {1, 2, 5, 8, 3, 1, 2, 6, 5, 7, 3, 2, 1, 4, 9};
    int size = sizeof(arr) / sizeof(arr[0]);

    // Check for unique values
    if (containsUniqueValues(arr, size)) {
        printf("The array contains unique values.\n");
    } else {
        printf("The array does not contain any unique values.\n");
    }

    return 0;
}



/*
run:

The array contains unique values.

*/

 



answered Mar 28, 2025 by avibootz
...