Drill

ProblemsPython › patterns

Collapse repeats in a sorted feed

easypatternsTwo pointersArraysPython

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

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

Solve it in the editor →

Where you start

def dedupe_sorted(ids: list[int]) -> list[int]:
    

Worked examples

CallResult
dedupe_sorted([1, 1, 2, 3, 3, 3])[1, 2, 3]
dedupe_sorted([1, 2, 3])[1, 2, 3]
dedupe_sorted([5, 5, 5, 5])[5]
dedupe_sorted([])[]

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 Python
def dedupe_sorted(ids: list[int]) -> list[int]:
    out = []
    for value in ids:
        if not out or out[-1] != value:
            out.append(value)
    return out

The same problem in another language

More patterns problems in Python