Skip to content

Instantly share code, notes, and snippets.

@chygoz2

chygoz2/removeInstance.js

Last active Apr 24, 2021
Embed
What would you like to do?
Algo friday 2 solution
function removeInstance(nums, val) {
if (!Array.isArray(nums)) throw new Error('Invalid input')
return nums.filter(entry => entry !== val).length
}
@meekg33k

This comment has been minimized.

Copy link

@meekg33k meekg33k commented Apr 19, 2021

Hello @chygoz2, thank you for participating in Week 2 of Algorithm Fridays.

This is a decent solution and I like that you included edge case checks and error-handling. Really clean!

I also like that you used the filter function to solve this problem but what do you think are the trade-offs with using the filter function? Is that the most optimal solution for this problem?

I've posted my solution here. Do let me know what you think.

@chygoz2

This comment has been minimized.

Copy link
Owner Author

@chygoz2 chygoz2 commented Apr 20, 2021

Thanks @meekg33k. I agree with you about the filter function affecting the space complexity of the algorithm, thus your solution is better in this regard.

The nature of the question revealed that it would be almost impossible to find a solution that wouldn't require going through the entire array, resulting in a time complexity of O(n). Your approach to solving it is quite interesting, and one I didn't think of.

In terms of algorithm complexity, O(n/2) is effectively O(n), since the growth rate of the solution is still linearly proportional to the size of the input, and constants are ignored in the calculation of algorithm complexities.
N.B I'm sure you already know that, just pointing it out to others that may be reading this.

I very much like your solution as it actually results in shorter program execution time, even though the time complexity is still linear.

@meekg33k

This comment has been minimized.

Copy link

@meekg33k meekg33k commented Apr 24, 2021

Very well said and I totally agree that in terms of algorithm complexity, O(n/2) is effectively O(n). You got a clean solution nevertheless!

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