26. Remove Duplicates from Sorted Array
easyGiven a sorted array, remove duplicates in-place and return the count of unique elements. The canonical 'slow + fast pointer for in-place dedup' pattern.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Return the number of unique elements k. Whatever you leave beyond nums[k-1] does not matter.
Constraints
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100nums is sorted in non-decreasing order.
Examples
Example 1
nums = [1,1,2]2, nums = [1,2,_]Explanation: The first two elements of nums should be 1 and 2. It does not matter what is left beyond the returned k.
Example 2
nums = [0,0,1,1,1,2,2,3,3,4]5, nums = [0,1,2,3,4,_,_,_,_,_]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Copying to a new array breaks the in-place rule.
Hint 2
Use a slow pointer that tracks 'where the next unique element lands' and a fast pointer that scans for new values.
Hint 3
When nums[fast] != nums[slow], advance slow and write nums[slow] = nums[fast]. Final k = slow + 1.
Solution approach
Reveal approach
Two pointers. Start slow = 0 (the last confirmed-unique index) and fast = 1. As fast scans, whenever nums[fast] differs from nums[slow] (i.e. we hit a new unique value), advance slow by one and copy nums[fast] into nums[slow]. After the scan, slow + 1 is the count of unique elements and nums[0..slow] holds them in order. Works because the array is sorted — equal values are adjacent, so a strict-not-equal check is enough.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- two-pointers
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
- Bloomberg
Practice these live with InterviewChamp.AI
Drill Remove Duplicates from Sorted Array and Arrays problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →