26 Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. 
It doesn't matter what you leave beyond the new length.

Naive Approach

The Idea: Erase the element if an adjacent duplicate is found from the array.

Complexity: O(n^2) time and O(1) space

int removeDuplicates(vector<int>& nums) {
    if (nums.empty()) return 0;
    else if (nums.size() == 1) return 1;

    for (int i = 1; i < nums.size(); i++) {
        if (nums.at(i - 1) == nums.at(i)) {
            nums.erase(nums.begin() + i);

    return nums.size();

Optimal Approach

The Idea: Add every unique occurrence in the array to the start, and ignore duplicates. That way the start of the array will only populate with unique elements.

Complexity: O(n) time and O(1) space

class Solution:
    def removeDuplicates(self, nums):
        :type nums: List[int]
        :rtype: int
        if len(nums) <= 1:
            return len(nums)

        i2 = 1
        for i in range(1, len(nums)):
            if nums[i] != nums[i-1]:
                nums[i2] = nums[i]
                i2 += 1

        return i2

Last updated