Skip to content

Instantly share code, notes, and snippets.

@Julisam
Last active April 19, 2021 13:54
Show Gist options
  • Save Julisam/95fe864720c75617a0a99806610bf72c to your computer and use it in GitHub Desktop.
Save Julisam/95fe864720c75617a0a99806610bf72c to your computer and use it in GitHub Desktop.
def remove_instance(nums, val):
"""
Given an array nums, and a value val, returns the new length of the array with the value removed
i.e. the number of items in nums with val
Input: nums=[5, 2, 2, 5, 3] and val = 5
Output: 3
"""
try:
#check for cases of an empty array
if len(nums) == 0:
return 0
else:
count=0
for i in nums:
if i != val:
count +=1
return count
except:
return 0
@meekg33k
Copy link

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

This is a decent solution; I like that you handled the case if the array is empty. However, your solution assumes that nums will always be an array because if I pass None as input to your function, it would break on line 10. Ideally you want to write robust code that takes care of invalid input.

Also, 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 to loop through the array?

I've posted my solution here. Do let me know what you think.

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