Skip to problem
←

Remove Duplicates from Sorted Array

Easy 0 attempts

Given an integer array nums sorted in nondecreasing order, modify it in place so its first k entries contain each distinct value exactly once, in increasing order. Return the integer k.

Write into the supplied array using constant extra space. Entries at indices k and beyond are ignored; you do not need to remove them or shorten the array. Return only the count, not a new array or an object.

For [1, 1, 2], write [1, 2] into the first two positions and return 2. The editor displays this as {"k": 2, "nums": [1, 2]} to show both the return value and the checked prefix.

A one-element array returns 1. If all values are identical, keep one occurrence in the first position and return 1.

Function contract

Implement removeDuplicates(nums).

Output: Return k and place the distinct values in the first k entries of nums. The editor checks both, displaying {k, nums: first k entries}; entries after k are ignored.

Example 1

Input
nums = [1,1,2]
Output
{"k":2,"nums":[1,2]}

Example 2

Input
nums = [1,1,1]
Output
{"k":1,"nums":[1]}
Constraints
  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order

Two Pointers

Since the array is sorted, duplicates are always adjacent. Keep a slow pointer k that marks where the next unique value should go. Walk a fast pointer through the array — whenever you see a value different from nums[k-1], write it at position k and advance k.

The invariant is that nums[0..k-1] contains the distinct values from all entries already scanned. Because the input is sorted, a different value starts a new group and can be written at the next free position. The write index never passes the read index, so overwriting the prefix does not destroy unread values.

javascript
function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  let k = 1;

  for (let i = 1; i < nums.length; i++) {
    if (nums[i] !== nums[k - 1]) {
      nums[k] = nums[i];
      k++;
    }
  }
  return k;
}

Time Complexity: O(n)

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript