Drill

ProblemsJavaScript › patterns

Collapse repeats in a sorted feed

easypatternsTwo pointersArraysJavaScript

A sorted export repeats an id whenever a row was touched twice. The importer wants each id once, still in order.

dedupeSorted(ids: list<int>) → list<int>

Solve it in the editor →

Where you start

function dedupeSorted(ids) {
  
}

Worked examples

CallResult
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;
}

The same problem in another language

More patterns problems in JavaScript