Mastering LeetCode Problem 0026
Problem 0026: Remove Duplicates from Sorted Array
When preparing for coding interviews, you’ll often see problems that look trivial at first glance, but actually test whether you truly understand common patterns like two pointers, in-place modification, and space complexity constraints.
LeetCode 26 – Remove Duplicates from Sorted Array – is exactly one of those problems.
In this post, we’ll walk through:
- The problem in plain English
- Why the sorted property is a big deal
- A clean two-pointer solution
- Step-by-step walkthrough with an example
- Time & space complexity
- Common mistakes and interview tips
1. Problem Statement in Plain English
You are given a sorted integer array nums in non-decreasing order, for example:
[1, 1, 1, 2, 2, 3, 4, 4]
Your task:
- Remove duplicate elements in-place, so each unique number appears only once.
- Do this using O(1) extra space (you are not allowed to use another array to store the result).
- Return the number of unique elements
k.
Important detail:
The judge will only look at the first k elements of nums. Anything after index k - 1 can be ignored.
1.1. Example
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
k = 2- First two elements are
[1, 2] -
_means “don’t care” – values after indexk - 1don’t matter.
2. Why the “Sorted” Property Matters
The fact that the array is sorted is not just a detail; it’s the cornerstone of the solution.
In a sorted array:
- All duplicates are grouped together.
- For any value
x, all its occurrences appear in a contiguous block.
That means we can:
- Scan from left to right,
- And simply detect when the current element is different from the last unique one.
No hash set, no extra data structures, no random searching.
One forward pass. Two pointers. Done.
3. Intuition: Two Pointers in Action
We’ll use a classic two-pointer technique:
-
i→ tracks the position of the last unique element in the array. -
j→ scans the array from left to right.
Initial idea:
- Start with
i = 0(the first element is always unique by default). - Move
jfrom index1to the end:- If
nums[j]is different fromnums[i], we found a new unique element:- Move
ione step to the right. - Copy
nums[j]intonums[i].
- Move
- If
By the end:
- All unique elements are packed at the start of the array, from
index 0toindex i. - The number of unique elements is
i + 1.
We are effectively compressing the array in-place.
4. The Clean Python Solution
Here is the final implementation in Python:
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# If the array is empty, there are no unique elements.
if not nums:
return 0
# i points to the position of the last unique element.
i = 0
# j scans through the array starting from index 1.
for j in range(1, len(nums)):
# When we find a new value (different from nums[i]),
# we move i forward and copy nums[j] into nums[i].
if nums[j] != nums[i]:
i += 1
nums[i] = nums[j]
# The number of unique elements is i + 1
return i + 1
4.1. How to Use It
Because removeDuplicates is an instance method, you should create an object of Solution before calling it:
if __name__ == "__main__":
nums = [1,1,1,1,2,2,2,2,2,3,3,3,3,4,4,4,5,5]
sol = Solution()
k = sol.removeDuplicates(nums)
print("k =", k) # number of unique elements
print("unique part =", nums[:k]) # only the first k elements matter
Example output:
k = 5
unique part = [1, 2, 3, 4, 5]
5. Step-by-Step Walkthrough
Let’s walk through a concrete example:
nums = [1, 1, 1, 2, 2, 3]
Initial state:
i = 0nums[i] = 1- The first element is always considered unique.
Now we start j from 1:
-
j = 1-
nums[j] = 1,nums[i] = 1→ same value → duplicate - Do nothing.
-
-
j = 2-
nums[2] = 1, still same asnums[i] = 1→ duplicate - Do nothing.
-
-
j = 3-
nums[3] = 2,nums[i] = 1→ different → new unique value - Move
iforward:i = 1 - Set
nums[1] = 2 - Array becomes:
[1, 2, 1, 2, 2, 3]
-
-
j = 4-
nums[4] = 2,nums[i] = 2→ duplicate - Do nothing.
-
-
j = 5-
nums[5] = 3,nums[i] = 2→ different → new unique value - Move
iforward:i = 2 - Set
nums[2] = 3 - Array becomes:
[1, 2, 3, 2, 2, 3]
-
End of loop:
i = 2- Number of unique elements:
k = i + 1 = 3 - Unique prefix:
nums[:3] = [1, 2, 3]
Everything after index 2 can be ignored.
6. Time and Space Complexity
This is where the solution really shines in an interview.
6.1. Time Complexity
We scan the array once with pointer j.
Each element is visited exactly one time.
where ( n ) is the length of the array.
6.2. Space Complexity
We don’t use any extra array or data structure.
We only store a couple of integer indices (i, j).
This satisfies the requirement of doing the removal in-place.
7. Common Mistakes in Interviews
Here are some mistakes I’ve seen (and made) around this problem:
7.1. Using Extra Data Structures
For example:
- Using a
setto track seen numbers. - Building a new list and returning that.
These might work logically, but they break the O(1) extra space requirement and the idea of in-place modification — which is often the main point of the question.
7.2. Forgetting the Edge Case: Empty Array
If nums is []:
- Accessing
nums[0]will cause an error. - A safe and clean check at the beginning:
if not nums: return 0
7.3. Misunderstanding What to Return
The function should return:
- The count of unique elements
k, not the modified array.
The platform will check:
- Only the first
kpositions innums.
So if your code returns the array instead of k, it’s wrong in the context of this particular problem.
7.4. Incorrect Method Call in OOP Code
In Python, if removeDuplicates is an instance method:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
...
Then calling:
Solution.removeDuplicates(nums)
is incorrect. You need an instance:
sol = Solution()
sol.removeDuplicates(nums)
8. Interview Takeaways
This problem is a perfect example of why interviewers love simple-looking questions:
- It tests whether you recognize the two-pointer pattern.
- It checks if you pay attention to constraints:
- in-place,
- O(1) extra space.
- It reveals how you handle edge cases (empty array, array with one element).
- It’s a good way to see how clean and readable your code is.
If you can solve this problem smoothly, explain your reasoning clearly, and justify the complexity, you’ll leave a strong impression.