Remove Duplicates from Sorted Array
Problem
You are given an integer array nums sorted in non-decreasing order. Modify it in place so that each distinct value appears only once, preserving the original relative order, and return the number of distinct values m. After your function returns, the first m positions of nums must hold the deduplicated sequence; whatever remains beyond index m - 1 is ignored. You must not allocate a second array.
numshas at most 50,000 elements; an empty array is allowed and returns 0.- Values are integers between -1000 and 1000.
numsis already sorted in non-decreasing order.
Examples
nums = [3, 3, 5, 8, 8, 8]→ returns3, andnumsbegins[3, 5, 8, ...].nums = [-2, -2, -2, 0, 4, 4, 9, 9, 9, 12]→ returns5, andnumsbegins[-2, 0, 4, 9, 12, ...].nums = [42]→ returns1; a single element is trivially distinct.
Hints
- Because the array is sorted, where are all the copies of a value located relative to each other?
- You need one index that scans the input and another that marks where the next unique value should be written.
- Read/write two pointers: advance
writeonly whennums[read]differs from the last value written.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.