Remove Duplicates from Sorted Array Cheat Sheet Javascript Solution.
The Remove Duplicate challenge is in the easy category and is a good start for understanding more challenging algorithms. I will focus on explaining a solution that works and not on the O time and space complexity.
Challenge:
“Given sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.” LeetCode
Notes:
-first element always unique-sorted array-remove duplicate-return the new length
Example:
arr = [3,3,4,4,4,5,5]new arr =[3,4,5]
0 1 2
|
ilength = index+1return 3
Explanation:
The two pointers i and j will increment through the array to check if they are equal to create a new array of unique element
[3,3,4,4,4,5,5]
| |
i j
1.Remove the edge case. If the array is empty there is no duplicate, 0 is falsy
if (!nums.length) return 0;
2. The pointer j will increment through the array
for(let j =1 ; j < nums.length ; j++);
3. Check if i is not equal to j
if (nums[i] !== nums[j]);
4. If not equal increment i
i=0;i++;
5. Set i pointer to where the j pointer was previously
if( nums[i])= nums[j] {
6. Once all the elements of the array have been checked, return the index + 1 because the index starts at 0
return i+1
Solution
var removeDuplicates = function(nums) {if(!nums.length) return 0;let i = 0;for(let j = 1 ; j < nums.length ; j++){if (nums[i] !== nums[j]){i++;nums[i] = nums[j]}}return i+1};