Drop the repeats
A feed sometimes sends the same id twice, and a clean list keeps only the first sighting.
- Keep the first occurrence of each value and drop any that repeat later.
- The relative order of the kept values is untouched.
dedupe(values: list<int>) → list<int>
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
std::vector<int> dedupe(std::vector<int> values) {
}
Worked examples
| Call | Result |
|---|---|
dedupe(std::vector<int>{1, 2, 3, 1, 2}) | std::vector<int>{1, 2, 3} |
dedupe(std::vector<int>{1, 1, 1}) | std::vector<int>{1} |
dedupe(std::vector<int>{}) | std::vector<int>{} |
dedupe(std::vector<int>{3, 1, 2, 1, 3}) | std::vector<int>{3, 1, 2} |
Hint
Carry a set of what you have already seen, and only push a value the first time you meet it.
Reference solution in C++
std::vector<int> dedupe(std::vector<int> values) {
std::set<int> seen;
std::vector<int> result;
for (int v : values) {
if (seen.insert(v).second) result.push_back(v);
}
return result;
}