<AI/>
enru
Все статьи

Remove duplicates from sorted array

LeetCode 26: Remove duplicates from a sorted array in place and return the number of unique elements.

Сложность
Легкая
Опубликовано
Темы
#array#two pointers
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

You are given an integer array nums sorted in ascending order. Write a function removeDuplicates that removes duplicate numbers from the array in place, i.e. without allocating additional memory. The relative order of the elements must be preserved.

Modify nums so that its first k elements contain the unique elements in the order they originally appeared in nums. The remaining elements of nums, as well as its size, don't matter.

The function must return an integer equal to the number of unique numbers in the array.

Constraints

  • The array contains from 1 to 104 elements
  • Values are in the range from -100 to 100
  • The array is sorted in ascending order

Examples

Input: [1, 1, 2]

Answer: 2

There are two unique numbers in the array: 1 and 2.

Solution

By the problem statement, the algorithm cannot allocate additional memory, so we can't use extra data structures such as a Map to count unique values. Instead, we keep a pointer pivot that tracks the position where the next unique element should be written in the modified array.

  • Set pivot = 1, since the zeroth element never needs to change: it's already in place
  • Run a loop over all elements of the input array except the first one.

Since the array is sorted in ascending order, detecting a new unique element is very easy. If two neighbouring elements are not equal, the second one is a new unique value.

If the element at index i is not equal to the element at index i - 1, we've found a new unique element. In this case we overwrite the element at index pivot with the value at index i and increment pivot by 1. This way we always move unique elements, in order, to the beginning of the array.

In the end, pivot equals the number of unique elements we've found.

typescript
export const removeDuplicates = (nums: number[]): number => {
  let pivot = 1;
 
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] != nums[i - 1]) {
      nums[pivot] = nums[i];
      pivot++;
    }
  }
 
  return pivot;
};

Complexity Analysis

n is the number of elements in the array.

Time Complexity

O(n), since we iterate over all elements of the array.

Space Complexity

O(1), since we don't create any additional data structures.