InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Remove Duplicates from Sorted Array

easy Original ↗ 00:00

Problem

You are given an integer array nums sorted in non-decreasing order. Rearrange it in place so that each distinct value appears exactly once, keeping the distinct values in their original (sorted) order. Return k, the number of distinct values.

Only the first k slots of nums matter afterward — the judge reads nums[0..k-1] and compares against the expected distinct values; whatever sits beyond index k - 1 is ignored. You may not allocate a second array (O(1) extra memory required).

Examples

  • nums = [1,1,2]k = 2, nums starts with [1,2] Two distinct values; the duplicate 1 is removed.
  • nums = [0,0,1,1,1,2,2,3,3,4]k = 5, nums starts with [0,1,2,3,4] Five distinct values remain, in ascending order.
  • nums = [7]k = 1, nums starts with [7] A single element has no duplicates.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order.
  • O(1) extra memory — expected O(n) time.

Think about it first

Hint 1 Because the array is sorted, all copies of a value sit next to each other. A value is a duplicate exactly when it equals its left neighbor.
Hint 2 Use one pointer to scan every element and another to mark where the next *new* value should be written. When do the two pointers move together, and when does only one move?
Hint 3 Keep `write` = length of the deduplicated prefix built so far. Scan with `read`; whenever `nums[read] != nums[write - 1]` (a value you haven't kept yet), copy it to `nums[write]` and bump `write`. Return `write`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug