Skip to content
Problem 26 · LeetCode 26(opens in a new tab)

Remove Duplicates from Sorted Array

EasyArrays

You are given an array of whole numbers, nums, sorted from smallest to largest. Some values may appear more than once.

Rearrange nums in place so that each distinct value appears once, in the same sorted order, at the front of the array. Return k, the number of distinct values. Only the first k slots are checked; whatever is left after them can be anything.

Example 1

Input:  nums = [2, 2, 5, 7, 7, 7]
Output: 3, nums = [2, 5, 7, _, _, _]
Why:    the distinct values are 2, 5 and 7
2 more examples and the constraints

Example 2

Input:  nums = [-4, -4, -4]
Output: 1, nums = [-4, _, _]
Why:    one value, repeated three times

Example 3

Input:  nums = [0, 3, 3, 8, 9, 9, 9, 12]
Output: 5, nums = [0, 3, 8, 9, 12, _, _, _]
Why:    five distinct values, kept in order

Constraints

  • 1 ≤ length of nums ≤ 30,000
  • −100 ≤ nums[i] ≤ 100
  • The values only go up or stay equal from left to right

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Collect, then copy backO(n)
  2. Read and write pointersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeExtra memory for 30,000 numbersVerdict
Collect, then copy backO(n)
Passes; uses a second list
Read and write pointersO(n)
Best; truly in place

n = length of nums. Both are one pass; the difference is memory.

Edge cases to test

  • One number. [5] gives k = 1; the loop never runs.
  • All the same. [-4, -4, -4] gives k = 1 with -4 at the front.
  • Already unique. Every value is written onto itself and k = n.
  • Long run at the end. [1, 2, 3, 3, 3] stops writing after 3, and k = 3.

Common mistakes

  • Looking ahead at nums[i + 1], which reads past the end of the array on the last value.
  • Returning the array, or the number of duplicates removed, instead of k.
  • Starting with k = 0 and then reading nums[k − 1] at index −1.

How to talk through it

  1. 1Clarify. Is it always sorted? Do the slots after k matter? Can the array be empty?
  2. 2Use the sort. Equal values are next to each other, so a value is new exactly when it differs from the one before it.
  3. 3Give the simple version. Collect the uniques into a new list and copy them back: O(n) time, but O(n) extra space.
  4. 4Code the two pointers. k is where the next unique value goes; i reads. Say why k never passes i.
  5. 5Test out loud. Run one number, all the same, and all distinct.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?