Remove Duplicates in Sorted Array- Easy Leetcode Solution using TypeScript
Understanding the 'Remove Duplicates from Sorted Array' Problem
The task is to remove duplicates from a sorted array of numbers and return the new length of the array without duplicates
Problem Type- Easy
https://leetcode.com/problems/remove-duplicates-from-sorted-array
O(n) Solution using Two Pointers
function removeDuplicates(nums) {
let k = 1;
if(nums.length < 1) {
return 0;
}
for(let i = 1; i < nums.length; i++) {
if(nums[i] != nums[i - 1]) {
nums[k] = nums[i];
k++;
}
}
return k;
};
Let me break it down for you:
I started by initializing a variable
k
to 1.I checked if the array
nums
is empty. If it is, I returned 0 since there are no duplicates to remove.I compared the current element
nums[i]
with its previous elementnums[i - 1]
.I used a
for
loop to iterate through the array starting from the second element (index 1) up to the last element.If the current element is not equal to the previous element, it means it's a unique number. So, I placed this unique number at position
k
in the array and incrementedk
by 1.Finally, I returned the value of
k
Learnings and Takeaways
Using a pointer or an index variable like
k
in the solution is important for ensuring that we only compare each element once and avoid duplicates and we don't have to use nested loops otheriwise our solution will be of O(n^2) or incorrect.Since we are not using any extra space that grows with the size of the input array, the space complexity remains constant at O(1).
Comment if I have committed any mistake. Let's connect on my socials. I am always open for new opportunities , if I am free :P