Last active
April 12, 2021 09:42
-
-
Save Amaka202/05f16a5e3fd17f1b9cde423954ed32d3 to your computer and use it in GitHub Desktop.
Algorithm Fridays Week 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
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
Yup Thanks alot Uduak for the feedback, I could have definitely improved the code by not creating an extra array and using a counter instead. And also for the cases I overlooked, I have learned today to account for every possible case in my code. Thanks!
I will take out time to update the code for future reference.
Looking forward to this week's problem!ππ»ππ»