Coding · stretch-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix

Remove Duplicates from Sorted Array

easytwo-pointersin-place

Problem

You are given an integer array nums sorted in non-decreasing order. Modify it in place so that each distinct value appears only once, preserving the original relative order, and return the number of distinct values m. After your function returns, the first m positions of nums must hold the deduplicated sequence; whatever remains beyond index m - 1 is ignored. You must not allocate a second array.

  • nums has at most 50,000 elements; an empty array is allowed and returns 0.
  • Values are integers between -1000 and 1000.
  • nums is already sorted in non-decreasing order.

Examples

  • nums = [3, 3, 5, 8, 8, 8] → returns 3, and nums begins [3, 5, 8, ...].
  • nums = [-2, -2, -2, 0, 4, 4, 9, 9, 9, 12] → returns 5, and nums begins [-2, 0, 4, 9, 12, ...].
  • nums = [42] → returns 1; a single element is trivially distinct.

Hints

  1. Because the array is sorted, where are all the copies of a value located relative to each other?
  2. You need one index that scans the input and another that marks where the next unique value should be written.
  3. Read/write two pointers: advance write only when nums[read] differs from the last value written.

Last reviewed 8 September 2026