Beyond Big O

Sorted deduplication

Sorted deduplication

Easy

Solution guide

Reveal solution guide — spoilers

Approach

  1. Build a new output sequence while scanning the sorted input once.
  2. Append a value when the output is empty or it differs from the last value appended. Skip every later occurrence in the same equal-value run.
  3. Return the new sequence without compacting or otherwise changing the input.

Why it works

Equal values are contiguous in a nondecreasing sequence. Keeping the first item of each run retains every distinct value exactly once, and retaining encounter order preserves ascending output. No set or search through earlier runs is necessary.

Complexity

O(n) time and O(1) auxiliary space excluding the returned sequence, which contains at most n values.

Edge cases to check

  • Empty input returns an empty list; an all-equal input returns one value.
  • Already-distinct and negative values follow the same rule.
  • Return the actual sequence, not its length, and leave the original input intact.
Editor options
Typing preferences

Saved in this browser.

Restoring local drafts…