LeetCode #26 Easy

Remove Duplicates from Sorted Array

Given a sorted array, remove duplicates in place so each value appears once. Return the new length k; the first k slots must hold the unique values.

arraytwo-pointers
Open on LeetCode ↗
02

Intuition

💡

Because the array is sorted, duplicates sit next to each other. A slow pointer marks the end of the unique prefix; a fast pointer scans ahead and, whenever it finds a new value, we extend the prefix.

03

Approach

1

The easy version uses extra space

You could collect the unique values into a new list and copy them back, but the problem demands an in-place solution with O(1) extra space. The one fact that makes in-place possible is that the array is sorted, so any duplicates are adjacent — we never have to look far to detect them.

2

Separate a 'read' pointer from a 'write' pointer

Keep a slow write pointer l marking the last slot of the unique prefix we've built, and a fast read pointer k scanning ahead. Because duplicates are adjacent, a value is new exactly when it differs from nums[l] (the last value we kept). When k finds such a new value, we advance l and copy it into place — overwriting a duplicate we no longer need.

3

Walk once; the length is l + 1

Start l = 0 (the first element is trivially unique). For each k from 1: if nums[k] != nums[l], do l += 1; nums[l] = nums[k]. Duplicates are simply skipped. At the end the first l + 1 slots hold the distinct values in order, and l + 1 is the answer. One pass, O(n) time, O(1) space.

04

Solution & live demo

python
1class Solution:
2 def removeDuplicates(self, nums):
3 l = 0
4 for k in range(1, len(nums)):
5 if nums[k] != nums[l]:
6 l += 1
7 nums[l] = nums[k]
8 return l + 1
05

Edge cases

No duplicates at all

Every nums[k] differs, so l advances each step and the whole array is kept.

All identical values

No nums[k] differs from nums[l]; l stays 0 and length 1 is returned.

Single element

The loop never runs; l + 1 = 1 is correct.

06

Complexity

Time
O(n)
Space
O(1)
Single pass with a read and a write pointer.