Skip to content

Drop Sorted Duplicates

Easy#two-pointers#in-place~15 min

The mission

Problem

A list of integers arrives sorted in non-decreasing order, so equal values sit next to each other in runs. Compact the list in place so every distinct value appears exactly once, in the original order. Return the count k of distinct values; the first k slots must hold them, and whatever remains after those slots is ignored.

Examples

Input:  nums = [1, 1, 2, 3, 3, 3]
Output: 3, and nums begins with [1, 2, 3]
Input:  nums = [4, 4, 4]
Output: 1, and nums begins with [4]
Why:    one long run collapses to a single value
Input:  nums = []
Output: 0
Why:    edge case, an empty list keeps nothing

Hints

0 / 3

Target time
O(n)
Target space
O(1)

Constraints

  • nums is sorted in non-decreasing order
  • compact the list in place

Stuck on the idea rather than the code? Two Pointers covers it.

Python 3Ctrl+Enter runs
Custom test case