Remove Duplicates from Sorted Array

Easy ArrayTwo Pointers

Problem

Given a sorted array nums, remove duplicates in place so each element appears once. Return the new length.

Example 1 Input: [1,1,2] Output: 2 (nums = [1,2,_])
Example 2 Input: [0,0,1,1,1,2,2,3,3,4] Output: 5 (nums = [0,1,2,3,4,...])

Constraints

Approach — Two Pointers

This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(n) time, O(1) extra space.

Solution code

Python

class Solution:
    def removeDuplicates(self, nums):
        if not nums:
            return 0
        k = 1
        for i in range(1, len(nums)):
            if nums[i] != nums[k - 1]:
                nums[k] = nums[i]
                k += 1
        return k

Java

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

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Remove Duplicates from Sorted Array interactively → ← All solutions