Skip to content

Instantly share code, notes, and snippets.

@Fredpwol
Last active April 27, 2021 14:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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
@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