Drill

ProblemsJava › patterns

Collapse repeats in a sorted feed

easypatternsTwo pointersArraysJava

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>

Java 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.

Solve it in Python →

Where you start

List<Integer> dedupeSorted(List<Integer> ids) {
    
}

Worked examples

CallResult
dedupeSorted(Main.<Integer>ls(1, 1, 2, 3, 3, 3))Main.<Integer>ls(1, 2, 3)
dedupeSorted(Main.<Integer>ls(1, 2, 3))Main.<Integer>ls(1, 2, 3)
dedupeSorted(Main.<Integer>ls(5, 5, 5, 5))Main.<Integer>ls(5)
dedupeSorted(Main.<Integer>ls())Main.<Integer>ls()

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 Java
List<Integer> dedupeSorted(List<Integer> ids) {
    List<Integer> out = new ArrayList<>();
    for (int id : ids) {
        if (out.isEmpty() || out.get(out.size() - 1) != id) out.add(id);
    }
    return out;
}

The same problem in another language

More patterns problems in Java