Remove Element
Problem Statement
Given an integer array of length and a value , remove all elements with the same absolute value as . This must be done in-place (without creating a new array).
def remove_element(arr, p):
# Your Code Here
Test Cases
Test Case 1
def test_case_1():
p = 5
arr = [3, 4, 5, 2, 1, -5, 5]
expected = [3, 4, 2, 1]
remove_element(arr, p)
assert expected == arr
Test Case 2
def test_case_2():
p = 1
arr = [3, 4, 5, 2, 1, -5, 5]
expected = [3, 4, 5, 2, -5, 5]
remove_element(arr, p)
assert expected == arr
Click Below to see the Solution
Algorithm
We will use a while loop to go through the indices, but if you remove an item, then don’t increase the index. This is because the array is updated as you go through the loop.
Code
def removeElement(nums, val):
i = 0
while i < len(nums):
if nums[i] == val:
nums.pop(i)
else:
i += 1
return nums
Runtime Analysis
We iterate through the array exactly once, so the computational complexity is .