Skip to content

Instantly share code, notes, and snippets.

@KingAshiru
Last active April 19, 2021 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KingAshiru/acc0e4b9a19e352a2000a36e2a12724c to your computer and use it in GitHub Desktop.
Save KingAshiru/acc0e4b9a19e352a2000a36e2a12724c to your computer and use it in GitHub Desktop.
class Solution:
def removeElement(self, nums, val) -> int:
# check for edge cases of None array, None value, or invalid values such as strings
if not nums:
return 0
if (not val) or (type(val) is not int) or (type(val) is not float):
return len(nums)
nextNonKey = 0
i = 0
# The idea is to check each element from the first index,
# If the element is a val we don't want to remove, we update that position using the nextNonKey tracker
# When we are done with all operations in the loop, nextNonKey would be the length of our desired array of values.
while i < len(nums):
if nums[i] != val:
nums[nextNonKey] = nums[i]
nextNonKey += 1
i += 1
return nextNonKey
# The while loop takes O(N), where N is the length of nums array
# Since the operation is done in place, we create no extra space, space complexity is O(1)
# In total we have Time - O(N), Space - O(1)
@meekg33k
Copy link

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

Really decent and robust solution you got here, that handles a lot of edge cases. This a huge improvement from last week's solution. Kudos to you! I also like that you are performing in-place operations thus ensuring good memory usage. Sweet!

The logic for your solution correctly centers around looping through the array to check for elements whose values are not equal to val. Do you think there's a faster way we can loop through the array?

I've posted my solution here. I am curious to know what you think.

@KingAshiru
Copy link
Author

KingAshiru commented Apr 19, 2021 via email

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