Remove Duplicates from Sorted Array (LeetCode 26): Solution and Explanation
You are given a sorted array that may contain repeated values. Rearrange it in place so that each distinct value appears once at the front, in the original order, and return how many distinct values there are. Whatever is left beyond that count does not matter.
Watch it run step by step
Try your own input and write the code →Intuition
The obvious approach builds a set or a new list of the unique values and copies them back. That uses O(n) extra memory, and the problem explicitly asks for the work to be done in place. Another naive idea is to delete each duplicate as you find it, but deleting from the middle of an array shifts every later element, so a run of duplicates can push the cost to O(n²).
Sortedness is the observation that unlocks this. In a sorted array, all copies of a value sit next to each other, so a value is new exactly when it differs from the last unique value you kept. You never need to look further back than that.
That suggests two pointers moving in the same direction. A slow pointer marks the last position of the unique prefix you are building, and a fast pointer scans every element. When fast finds a value different from nums[slow], you grow the prefix by one and copy the value there. Since slow never passes fast, you only ever overwrite slots whose values have already been read, which is what makes the in-place version safe.
Approach: Slow and fast two pointers
- If the array is empty, return 0.
- Set
slow = 0. The first element is always unique, so the prefix starts with it. - Move
fastfrom index 1 to the end of the array. - When
nums[fast] != nums[slow], incrementslowand copynums[fast]intonums[slow]. - When the values are equal, do nothing and let
fastmove on, skipping the duplicate. - Return
slow + 1, the length of the unique prefix.
Step-by-step example
nums = [0,0,1,1,1,2,2,3,3,4]
slowstarts at 0 holding 0. Atfast = 1the value is also 0, so it is skipped.- At
fast = 2the value 1 differs from 0, soslowbecomes 1 andnums[1] = 1. Indices 3 and 4 hold 1 and are skipped. - At
fast = 5the value 2 is new, soslowbecomes 2 andnums[2] = 2. Index 6 is skipped. - At
fast = 7the value 3 is new, sonums[3] = 3, and atfast = 9the value 4 is new, sonums[4] = 4. - The loop ends with
slow = 4, so the function returns 5 and the array begins with [0, 1, 2, 3, 4].
Code: Python, Java, C++
1class Solution:
2 def removeDuplicates(self, nums: List[int]) -> int:
3 if not nums:
4 return 0
5
6 slow = 0
7 for fast in range(1, len(nums)):
8 if nums[fast] != nums[slow]:
9 slow += 1
10 nums[slow] = nums[fast]
11
12 return slow + 11class Solution {
2 public int removeDuplicates(int[] nums) {
3 if (nums.length == 0) return 0;
4
5 int slow = 0;
6 for (int fast = 1; fast < nums.length; fast++) {
7 if (nums[fast] != nums[slow]) {
8 slow++;
9 nums[slow] = nums[fast];
10 }
11 }
12 return slow + 1;
13 }
14}1class Solution {
2public:
3 int removeDuplicates(vector<int>& nums) {
4 if (nums.empty()) return 0;
5
6 int slow = 0;
7 for (int fast = 1; fast < nums.size(); fast++) {
8 if (nums[fast] != nums[slow]) {
9 slow++;
10 nums[slow] = nums[fast];
11 }
12 }
13 return slow + 1;
14 }
15};Time and space complexity
O(n)
The fast pointer visits each element exactly once and each visit does one comparison and at most one write.
O(1)
Only two integer indices are used, and the unique values are written back into the input array.
Other approaches
Set then copy back (time O(n), space O(n))
Collect the distinct values in order, for example with a dictionary or by checking against the last appended value, then write them into the front of nums. It is easy to reason about but uses O(n) extra memory, which defeats the in-place requirement.
Common mistakes
- Returning a new deduplicated list. The caller reads the returned count and then the first k slots of the same input array, so a separate list is simply ignored.
- Returning
slowinstead ofslow + 1.slowis an index, so the count of unique values is one more. - Incrementing
slowafter the copy instead of before, which overwrites the last kept value. - Trying to shrink the list with
popordelinside the loop. Removing items shifts the indices you are iterating over and makes the run time quadratic.
Frequently asked questions
Why does this only work on a sorted array?
The algorithm assumes that duplicates are adjacent, so comparing with the last kept value is enough. In an unsorted array a repeat could appear anywhere later, and you would need a hash set to remember what you have seen.
What should the elements after k contain?
Nothing in particular. The checker only reads the first k elements, where k is the returned count, so leftover values beyond that point can be anything.
How do I allow each value at most twice?
Compare nums[fast] with nums[slow - 1] instead of nums[slow] and keep a write index. That is the follow-up problem, and the same pattern extends to at most k copies by comparing with the element k positions back.
What is the time and space complexity?
The time is O(n) because each element is read once, and the space is O(1) because the result is written into the input array.