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.
Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k.
The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored.
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Solution
So the array is sorted, means numbers are in increasing order but duplicates can be there like [0,0,1,1,2,2].
The question says remove duplicates in place, which basically means we don’t create new array.
We just take the same array and push all unique values to the front.
My way to think is very simple:
- Take two variables
- x stays at the place where the last unique element is
- i runs the whole array
- whenever I find a value bigger than nums[x], that means it’s a new unique value
- so I increase x and put that value at nums[x]
That’s it.
Code:
var removeDuplicates = function(nums) {
let x = 0
for(let i = 0 ; i < nums.length; i++){
if(nums[x] < nums[i]){
x = x + 1
nums[x] = nums[i]
}
}
return x + 1
}
Now why x + 1?
Because x is index.
Index starts from 0.
But the answer they want is count of unique values.
So if last unique element is at index 2, then total unique are 3 → that’s why x + 1.
This is literally the whole logic. Simple two-pointer trick. If you want I can also explain the dry-run in the same simple tone.
Similar to this question there is one more question can solve to get better at it.
leetCode Question no 27.
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).

Top comments (0)