Remove Duplicates From Sorted Array
Easy
Difficulty
O(n)
Time Complexity
O(1)
Space Complexity
Two Pointer
Approach
Jan 18, 2026
Last Updated
Problem Statement
You are given an integer array
After removing the duplicates, return the number of unique elements, denoted as
Note:
* The order of the unique elements should remain the same as in the original array.
* It is not necessary to consider elements beyond the first k positions of the array.
* To be accepted, the first k elements of nums must contain all the unique elements.
Return
nums sorted in non-decreasing order. Your task is to remove duplicates from nums in-place so that each element appears only once.
After removing the duplicates, return the number of unique elements, denoted as
k, such that the first k elements of nums contain the unique elements.
Note:
* The order of the unique elements should remain the same as in the original array.
* It is not necessary to consider elements beyond the first k positions of the array.
* To be accepted, the first k elements of nums must contain all the unique elements.
Return
k as the final result.Examples
Example 1:
Input: [1,1,2,3,4]
Output: [1,2,3,4]
Explanation: You should return k = 4 as we have four unique elements.
Example 2:
Input: nums = [2,10,10,30,30,30]
Output: [2,10,30]
Explanation: You should return k = 3 as we have three unique elements.
Optimal Solution
The optimal solution for the problem is perhaps the most intuitive one. The key is to not overthink it.
You take two pointers,
When
At the end of the loop, ie, when
You take two pointers,
i and j. i keeps the index of the last unique element encountered in the array and j moves forward to find the next unique element.
When
j finds the next unique element, we increment i and set nums[i] = nums[j] to contain the new unique element.
At the end of the loop, ie, when
j reaches the end of the array, i will now contain the index of the last unique element. We return i+1 to indicate the number of unique elements and not the last index of the unique element, hence the +1.Two Pointer approach
RDfSA.javaTwo Pointer approach
1class Solution {
2 public int removeDuplicates(int[] nums) {
3 int i=0;
4
5 for (int j=1; j<nums.length; j++){
6 if (nums[j]!= nums[i]){
7 i++;
8 nums[i] = nums[j];
9
10 }
11 }
12
13 return i+1;
14 }
15}Complexity Analysis
Time Complexity
Two Pointer: O(n)
Space Complexity
Two Pointer: O(1)