Remove Duplicates from Sorted Array Easy 0 attempts
LeetCode ↗

Remove Duplicates from Sorted Array

Easy ArrayTwo Pointers LeetCode

You're given nums, an integer array already sorted in non-decreasing order. Modify it in-place so every distinct value appears exactly once, then return k, the number of distinct values. After your changes, the first k positions of nums must hold those distinct values in their original relative order — whatever sits past index k doesn't matter.

Edge cases: A single-element array. An array where every element is identical.

Input Format
Implement removeDuplicates(nums). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
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.

Sample Input and Output

Example 1 · Run Sample

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
Test Cases (2)
Case 1
Args: [[1,1,2]] Expected: {"k":2,"nums":[1,2]}
Case 2
Args: [[1,1,1]] Expected: {"k":1,"nums":[1]}

Approach: 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.

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)

Saved in this browser only. Private to you.

JavaScript