Skip to content

Instantly share code, notes, and snippets.

@Amaka202
Last active April 12, 2021 09:42
Show Gist options
  • Select an option

  • Save Amaka202/05f16a5e3fd17f1b9cde423954ed32d3 to your computer and use it in GitHub Desktop.

Select an option

Save Amaka202/05f16a5e3fd17f1b9cde423954ed32d3 to your computer and use it in GitHub Desktop.
Algorithm Fridays Week 1
// Given a sorted array nums, write a function to remove the
// duplicates from the array such that each element appears
// only once. Your function should return the new length
const removeDuplicateArrayElements = (nums) => {
const noDuplicatesArray = [];
for(let i = 0; i < nums.length; i++){
//compare adjacent elements of the array and check if they
//are the same since the array is sorted already, skip if true.
if(nums[i] === nums[i + 1]) continue;
noDuplicatesArray.push(nums[i]);
}
return noDuplicatesArray.length;
}
console.log(removeDuplicateArrayElements([0,0,1,1,2,2,3,3,4,4,4,5,5,5,6])
); //7
@osahondev
Copy link

Nice Amaka. This is actually very good. However I feel your space complexity of O(n) can be reduced to O(1). What if rather than pushing into a new array, you define a counter and increment when nums[i] != nums[i+1]? Let me know what your think.

Yes I didn't think of that😫😫. Thank you so much, since the deadline has elapsed I will apply the feedback to subsequent problems. I am already excited about this program Algorithm Fridays as I hope to improve on my problem solving skills.💃🏻

Great stuff Amaka and Weldone!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment