sagelearnai

Remove Duplicates from Sorted Array

Difficulty: Easy · Pattern: Two Pointers · LeetCode #26

nums is sorted in non-decreasing order. Remove duplicates in place so each unique value appears once, keeping the order. Return k, the number of unique values; the first k slots of nums must hold them. (The tests show [k, first k elements].)

Examples

text
[1, 1, 2]                     →  k = 2, nums starts [1, 2]
[0, 0, 1, 1, 1, 2, 2, 3, 3, 4] →  k = 5, nums starts [0, 1, 2, 3, 4]

Hints

  1. Because the array is sorted, duplicates are adjacent.
  2. Keep a write index k; copy nums[i] to nums[k] only when it differs from nums[k−1].

Approach

k marks the end of the unique prefix. For each element, compare it with the last kept value nums[k−1]; if it's different, write it at nums[k] and increment k. Sortedness guarantees that equal values are contiguous, so one comparison suffices.

Complexity

Time: O(n). Space: O(1).

Python solution
def removeDuplicates(nums):
    if not nums:
        return 0
    k = 1
    for i in range(1, len(nums)):
        if nums[i] != nums[k - 1]:
            nums[k] = nums[i]
            k += 1
    return k
JavaScript solution
function removeDuplicates(nums) {
  if (!nums.length) return 0;
  let k = 1;
  for (let i = 1; i < nums.length; i++) if (nums[i] !== nums[k - 1]) nums[k++] = nums[i];
  return k;
}