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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!