Remove Duplicates from Sorted Array (LeetCode 26): Solution and Explanation

Easy
Array
Two Pointers

You are given a sorted array that may contain repeated values. Rearrange it in place so that each distinct value appears once at the front, in the original order, and return how many distinct values there are. Whatever is left beyond that count does not matter.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The obvious approach builds a set or a new list of the unique values and copies them back. That uses O(n) extra memory, and the problem explicitly asks for the work to be done in place. Another naive idea is to delete each duplicate as you find it, but deleting from the middle of an array shifts every later element, so a run of duplicates can push the cost to O(n²).

Sortedness is the observation that unlocks this. In a sorted array, all copies of a value sit next to each other, so a value is new exactly when it differs from the last unique value you kept. You never need to look further back than that.

That suggests two pointers moving in the same direction. A slow pointer marks the last position of the unique prefix you are building, and a fast pointer scans every element. When fast finds a value different from nums[slow], you grow the prefix by one and copy the value there. Since slow never passes fast, you only ever overwrite slots whose values have already been read, which is what makes the in-place version safe.

Approach: Slow and fast two pointers

  1. If the array is empty, return 0.
  2. Set slow = 0. The first element is always unique, so the prefix starts with it.
  3. Move fast from index 1 to the end of the array.
  4. When nums[fast] != nums[slow], increment slow and copy nums[fast] into nums[slow].
  5. When the values are equal, do nothing and let fast move on, skipping the duplicate.
  6. Return slow + 1, the length of the unique prefix.

Step-by-step example

nums = [0,0,1,1,1,2,2,3,3,4]
  1. slow starts at 0 holding 0. At fast = 1 the value is also 0, so it is skipped.
  2. At fast = 2 the value 1 differs from 0, so slow becomes 1 and nums[1] = 1. Indices 3 and 4 hold 1 and are skipped.
  3. At fast = 5 the value 2 is new, so slow becomes 2 and nums[2] = 2. Index 6 is skipped.
  4. At fast = 7 the value 3 is new, so nums[3] = 3, and at fast = 9 the value 4 is new, so nums[4] = 4.
  5. The loop ends with slow = 4, so the function returns 5 and the array begins with [0, 1, 2, 3, 4].

Code: Python, Java, C++

1class Solution:
2    def removeDuplicates(self, nums: List[int]) -> int:
3        if not nums:
4            return 0
5
6        slow = 0
7        for fast in range(1, len(nums)):
8            if nums[fast] != nums[slow]:
9                slow += 1
10                nums[slow] = nums[fast]
11
12        return slow + 1

Time and space complexity

Time

O(n)

The fast pointer visits each element exactly once and each visit does one comparison and at most one write.

Space

O(1)

Only two integer indices are used, and the unique values are written back into the input array.

Other approaches

Set then copy back (time O(n), space O(n))

Collect the distinct values in order, for example with a dictionary or by checking against the last appended value, then write them into the front of nums. It is easy to reason about but uses O(n) extra memory, which defeats the in-place requirement.

Common mistakes

  • Returning a new deduplicated list. The caller reads the returned count and then the first k slots of the same input array, so a separate list is simply ignored.
  • Returning slow instead of slow + 1. slow is an index, so the count of unique values is one more.
  • Incrementing slow after the copy instead of before, which overwrites the last kept value.
  • Trying to shrink the list with pop or del inside the loop. Removing items shifts the indices you are iterating over and makes the run time quadratic.

Frequently asked questions

Why does this only work on a sorted array?

The algorithm assumes that duplicates are adjacent, so comparing with the last kept value is enough. In an unsorted array a repeat could appear anywhere later, and you would need a hash set to remember what you have seen.

What should the elements after k contain?

Nothing in particular. The checker only reads the first k elements, where k is the returned count, so leftover values beyond that point can be anything.

How do I allow each value at most twice?

Compare nums[fast] with nums[slow - 1] instead of nums[slow] and keep a write index. That is the follow-up problem, and the same pattern extends to at most k copies by comparing with the element k positions back.

What is the time and space complexity?

The time is O(n) because each element is read once, and the space is O(1) because the result is written into the input array.