Command Palette

Search for a command to run...

Problem 6.3 · Two PointersEasy

Remove Duplicates from Sorted Array

What it teaches: Keep an element only if it differs from the last kept one: read/write pointers on sorted data.

Practise it on judges as “Remove Duplicates from Sorted Array”.

The problem

nums is sorted. Remove duplicates in place so each value appears once, keeping order. Return the number of unique values k; the first k elements of nums must hold them.

Example 1

Input: nums = [1, 1, 2]
Output: 2

nums starts with [1, 2].

Example 2

Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: 5

nums starts with [0, 1, 2, 3, 4].

Constraints

  • 1 ≤ nums.length ≤ 3 × 10⁴
  • Sorted non-decreasing
  • In place

Pattern clues in the wording

  • → Sorted, so duplicates are neighbours
  • → In place, return the new length

These clues point to Two Pointers: Read and Write: A fast pointer reads every element and a slow pointer marks where the next kept element should be written.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int removeDuplicates(int[] nums) {
        int write = 1;
        return write;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
nums = [1,1,2]
2
2
nums = [0,0,1,1,1,2,2,3,3,4]
5

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: compare with the last kept value

Time O(n) Space O(1)

write = 1. For each read from 1, if nums[read] != nums[write − 1], copy it to nums[write++].

Approach 1
class Solution {
    public int removeDuplicates(int[] nums) {
        int write = 1;
        for (int read = 1; read < nums.length; read++) {
            if (nums[read] != nums[write - 1]) nums[write++] = nums[read];
        }
        return write;
    }
}

Verdict: One pass in place.

Before you submit

Edge cases and common mistakes

Test these inputs

  • One element
  • All equal
  • No duplicates

Mistakes people make

  • Comparing with nums[read − 1] works here too, but fails in the "at most two copies" follow-up; comparing with the last written value generalises.

Interview

Follow-up questions

What if each value may appear at most twice?