Two Pointers · 054Easy
Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates IN PLACE so each unique element appears once, keeping the relative order. Return k, the number of unique elements; the first k slots of nums must hold them. What is left beyond k does not matter.
Constraints
- 1 <= nums.length <= 3 * 10^4
- -100 <= nums[i] <= 100
- nums is sorted in non-decreasing order.
- You must do it in place with O(1) extra memory.
Examples
removeDuplicates([1, 1, 2]) -> 2, nums starts [1, 2, _] removeDuplicates([0,0,1,1,1,2,2,3,3,4]) -> 5, nums starts [0,1,2,3,4] removeDuplicates([1]) -> 1 removeDuplicates([1, 1, 1]) -> 1, nums starts [1, _, _] // all identical removeDuplicates([1, 2, 3]) -> 3, nums starts [1, 2, 3] // no duplicates to remove removeDuplicates([-100, -100, 0, 0, 100]) -> 3, nums starts [-100, 0, 100] // negatives
Edge cases
- A single element.
- All elements identical — the answer is 1.
Show the target complexity (spoiler)
- Naive
- O(n) time, O(n) space — build a fresh array of uniques, which the constraint forbids.
- Target
- O(n) time, O(1) space — a slow write pointer and a fast read pointer; write only when the value differs from the last written one.
Solve it
By hand, in your editor. The runner checks answers and timing.
git clone https://github.com/sarmadkung/optimal-round cd optimal-round # open problems/02-two-pointers/054-remove-duplicates-from-sorted-array.js ./practice c 054