LearnFrenzy
Sign in Take a free test

Memory Allocation · Memory Programs · Question 7

Remove duplicates from an unsorted array with malloc in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Return a new heap array with each value of an unsorted array (values 0–99) once, in first-seen order.

Solution
main.c
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

int *unique_values(const int *a, size_t n, size_t *out_n) {
    bool *seen = calloc(100, sizeof *seen);          /* zeroed: nothing seen yet */
    int *out = malloc(n * sizeof *out);
    if (seen == NULL || out == NULL) {
        free(seen);
        free(out);
        return NULL;
    }
    size_t k = 0;
    for (size_t i = 0; i < n; i++)
        if (a[i] >= 0 && a[i] < 100 && !seen[a[i]]) {
            seen[a[i]] = true;
            out[k++] = a[i];
        }
    free(seen);
    *out_n = k;
    return out;
}

int main(void) {
    int a[] = {4, 7, 4, 1, 7, 9, 1, 4};
    size_t k;
    int *u = unique_values(a, 8, &k);
    if (u == NULL)
        return 1;
    for (size_t i = 0; i < k; i++)
        printf("%d ", u[i]);
    printf("(%zu unique)\n", k);
    free(u);
    return 0;
}

Output Verified by compiling and running

4 7 1 9 (4 unique)

A zeroed "seen" table from calloc() answers "have I met this value?" in O(1), so the whole job is O(n). Note the combined failure path: freeing both pointers is safe because free(NULL) does nothing.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links