Algo-Sim › Two Pointers

Remove Duplicates from Sorted Array

Easy · Two Pointers · step through it in Java, Python and C++ on your own input

Compact a sorted array in place so each value appears once, and return how many unique values there are.

Problem

Given an integer array nums sorted in non-decreasing order, rearrange it in place so that each distinct value appears once, in the original order, at the front of the array. Return k, the number of distinct values; whatever is left after the first k positions does not matter.

Constraints

Edge cases to test

Follow-up questions

What if each value may appear at most twice?
Compare with the element two places back in the written part: write nums[i] if it differs from nums[k − 2] (LC 80). Same O(n), O(1).
What if the array is not sorted?
Use a hash set to drop repeats, or sort first: O(n) with O(n) space, or O(n log n) in place.

Solution

Java

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];
            write++;
        }
    }
    return write;
}

Python

def remove_duplicates(nums):
    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int removeDuplicates(vector<int> &nums) {
        int write = 1;
        for (int read = 1; read < int(nums.size()); read++) {
            if (nums[read] != nums[write - 1]) {
                nums[write] = nums[read];
                write++;
            }
        }
        return write;
    }
};

More Two Pointers problems