progress

~/problems / Two pointers

Remove Duplicates from Sorted Array

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

Write dedupe_sorted(nums: list[int]) -> int. nums is sorted; rearrange it in place so its first k slots hold each distinct value once, in order, and return k. What's left after slot k doesn't matter.

nums = [1, 1, 2, 4, 4, 4, 7]
k = dedupe_sorted(nums)    # 4
nums[:k]                   # [1, 2, 4, 7]

dedupe_sorted([])          # 0

Up to 3·10^5 values. Use O(1) extra memory: a set or new list fails the memory test. ⭐ Bonus: a speed test earns a star in O(n) (no del).

Show hint

keep a second index for where the next new value goes. In a sorted list, a value is new exactly when it differs from the last one written.

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc