Skip to content

Instantly share code, notes, and snippets.

Last active Apr 27, 2021
What would you like to do?
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
if nums[ptr1] != val:
res += 1
if nums[ptr2] != val:
res += 1
ptr1 += 1
ptr2 -= 1
return res
Copy link

Fredpwol commented Apr 19, 2021

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