Collapse repeats in a sorted feed
A sorted export repeats an id whenever a row was touched twice. The importer wants each id once, still in order.
- The input arrives sorted ascending, so equal values are always adjacent.
- Each distinct value survives once, in the order it first appeared.
- An empty feed comes back empty.
dedupeSorted(ids: 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> dedupeSorted(std::vector<int> ids) {
}
Worked examples
| Call | Result |
|---|---|
dedupeSorted(std::vector<int>{1, 1, 2, 3, 3, 3}) | std::vector<int>{1, 2, 3} |
dedupeSorted(std::vector<int>{1, 2, 3}) | std::vector<int>{1, 2, 3} |
dedupeSorted(std::vector<int>{5, 5, 5, 5}) | std::vector<int>{5} |
dedupeSorted(std::vector<int>{}) | std::vector<int>{} |
Hint
Because it is sorted you only ever need to compare against the value you kept last. Walk forward and keep a value only when it differs from that one.
Reference solution in C++
std::vector<int> dedupeSorted(std::vector<int> ids) {
std::vector<int> out;
for (int id : ids) {
if (out.empty() || out.back() != id) out.push_back(id);
}
return out;
}