Problems › JavaScript › patterns
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>
Where you start
function dedupeSorted(ids) {
}
Worked examples
| Call | Result |
|---|---|
dedupeSorted([1,1,2,3,3,3]) | [1,2,3] |
dedupeSorted([1,2,3]) | [1,2,3] |
dedupeSorted([5,5,5,5]) | [5] |
dedupeSorted([]) | [] |
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 JavaScript
function dedupeSorted(ids) {
const out = [];
for (const id of ids) {
if (out.length === 0 || out[out.length - 1] !== id) out.push(id);
}
return out;
}