Remove Duplicate Values
Duplicate removal combines membership checks with a separate result collection.
What is Remove Duplicate Values?
Duplicate removal combines membership checks with a separate result collection.
Remove repeated array values while preserving order.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
int input[] = {1, 2, 1, 3, 2, 4}, output[6], size = 0;
// Keep the first occurrence of every value.
for (int i = 0; i < 6; ++i) { int seen = 0; for (int j = 0; j < size; ++j) if (output[j] == input[i]) seen = 1; if (!seen) output[size++] = input[i]; }
for (int i = 0; i < size; ++i) printf("%s%d", i ? " " : "", output[i]); puts("");
}
1 2 3 4
C++
main.cpp
#include <iostream>
#include <unordered_set>
#include <vector>
int main() {
std::vector input{1, 2, 1, 3, 2, 4}; std::vector<int> output; std::unordered_set<int> seen;
// Insert returns true only for the first occurrence.
for (int value : input) if (seen.insert(value).second) output.push_back(value);
for (size_t i = 0; i < output.size(); ++i) std::cout << (i ? " " : "") << output[i]; std::cout << '\n';
}
1 2 3 4
C and C++ comparison
Append a value only when it does not already occur in the output built so far.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.