Skip to content
LEETFLIX

Remove Duplicates from Sorted Array

Solve on LeetCode

Easy · slow pointer unique prefix. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 26. Remove Duplicates from Sorted Array. The copyrighted prompt is on LeetCode. This page is a working slow pointer unique prefix for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[1, 1, 2]

Output

2

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Write uniques into the prefix

Because the array is sorted, duplicates are adjacent. w is the next write slot; a new value gets copied there.

The first w slots become the unique prefix. The rest of the array is junk the caller ignores.

Algorithm

  1. Start w = 1 (the first value is already unique).
  2. For each later x, if it differs from nums[w-1], write it at w and increment w.
  3. Return w.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def removeDuplicates(self, nums: list[int]) -> int:        if not nums:            return 0        w = 1        for i in range(1, len(nums)):            if nums[i] != nums[w - 1]:                nums[w] = nums[i]                w += 1        return w
Watch this run

03

Interactive walkthrough

Playing “Write uniques into the prefix”. Edit the input, hit Run, then scrub.

Approach: Write uniques into the prefix

Loading animation…