Remove Duplicates from Sorted Array

Easy

Given a sorted array nums, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements. The relative order of elements should be kept the same.

Examples

InputOutput
nums = [1,1,2]2, nums = [1,2,_]
nums = [0,0,1,1,1,2,2,3,3,4]5, nums = [0,1,2,3,4,_,_,_,_,_]

Python Solution

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

JavaScript Solution

function removeDuplicates(nums) {
  if (!nums.length) return 0;
  let write = 1;
  for (let read = 1; read < nums.length; read++) {
    if (nums[read] !== nums[read - 1]) {
      nums[write++] = nums[read];
    }
  }
  return write;
}

Step-by-Step Explanation

  1. Use two pointers: read scans the array, write is where we place the next unique element.
  2. When we see a new value (different from previous), copy it to write and increment write.
  3. Return write as the count of unique elements.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

ArrayTwo Pointers

Related Problems

Related Tools

All Problems