Skip to content

Instantly share code, notes, and snippets.

@Fredpwol
Last active April 27, 2021 14:38
Show Gist options
  • Save Fredpwol/9e468f22dc959554f9c3c2603c6f54e7 to your computer and use it in GitHub Desktop.
Save Fredpwol/9e468f22dc959554f9c3c2603c6f54e7 to your computer and use it in GitHub Desktop.
Remove All Instance
def remove_all_instances(nums, val):
"""
This returns the number of values in num that isn't equal to val
its time complexity is O(n/2) because I used two pointers to navigate from left to right
and from right to left the both meet at p = n/2. while space O(1)
"""
if nums == None: return 0
if val == None: return 0
res = 0
ptr1 = 0
ptr2 = len(nums) - 1
while ptr1 <= ptr2:
if ptr1 == ptr2: #once the two pointers meet at the center for odd lengths we only use the value for one of the pointers to check.
if nums[ptr1] != val:
res += 1
break
if nums[ptr1] != val:
res += 1
if nums[ptr2] != val:
res += 1
ptr1 += 1
ptr2 -= 1
return res
@meekg33k
Copy link

Hello @Fredpwol, thank you for participating in Week 2 of Algorithm Fridays and congratulations, you are the winner of the $20 award 🎉🎉.

Your solution was selected because it is most optimal in terms of memory and time complexity. It is also robust and takes care of edge cases such as when any of the input values is None.

I have made a blog post here about the different solutions and about you as the winner for Week 2 of Algorithm Fridays.

We will contact you in less than 24 hours for your award.

Congratulations once again!

@Fredpwol
Copy link
Author

Thank you very much, I'm very grateful 😊.

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