Last active
April 27, 2021 14:38
-
-
Save Fredpwol/9e468f22dc959554f9c3c2603c6f54e7 to your computer and use it in GitHub Desktop.
Remove All Instance
This file contains 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much, I'm very grateful 😊.