Remove duplicates from sorted array

Asked atNinjacartTwilio
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an integer array nums sorted in non-decreasing order, remove all duplicates in-place so that each unique element appears only once.

Return the number of unique elements in the array.

If the number of unique elements be** k,** then,

  • Change the array nums** such that the first k **elements of nums contain the unique values in the order that they were present originally.
  • The remaining elements, as well as the size of the array does not matter in terms of correctness.
  • The driver code will assess correctness by printing and checking only the first k elements of the modified array.

An array sorted in **non-decreasing order is an array where every element to the right of an element is either equal to or greater **in value than that element.

Input: nums = [0, 0, 3, 3, 5, 6] Output: 4 Explanation: Resulting array = [0, 3, 5, 6, _, _] There are 4 distinct elements in nums and the elements marked as _ can have any value.

Input: nums = [-2, 2, 4, 4, 4, 4, 5, 5] Output: 4 Explanation: Resulting array = [-2, 2, 4, 5, _, _, _, _] There are 4 distinct elements in nums and the elements marked as _ can have any value.

Input: nums = [-30, -30, 0, 0, 10, 20, 30, 30] Select the possible resulting array.

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.

cpp

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        
    }
};

java

class Solution {
    public int removeDuplicates(int[] nums) {
        
    }
}

python

class Solution:
    def removeDuplicates(self, nums: list[int]) -> int:

javascript

class Solution {
    removeDuplicates(nums) {

    }
}

csharp

public class Solution {
    public int removeDuplicates(List<int> nums) {
        
    }
}

go

func removeDuplicates(nums []int) int {
    //your code goes here
}
Stuck? Show a way to structure it+
  1. 01State that the input is sorted and mutation is allowed
  2. 02Initialize the write pointer after the first item
  3. 03Scan with a read pointer and compare against the last kept item
  4. 04Return the write length

Reference answer

Then expect these follow-ups

  • How would you allow at most two copies?

    Tests: follow-up reasoning

  • What changes if the array is unsorted?

    Tests: constraint adaptation

Hiring now

Twilio has 109 open roles right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Staff Software Engineer, Mobile (P4)

    Remote

  • Software Engineer (L3) Email

    Remote

  • Staff, Software Engineer (L4)

    Remote

Or practice this question first

Next question