The problem is to remove all instances of a specific value in a given array in-place and return the new length of the array. The order of elements can be changed, and the elements beyond the new length do not matter.
Input: nums = [3, 2, 2, 3], val = 3
Output: 2, nums = [2, 2, _, _]
Note: The underscore (_) represents irrelevant values beyond the desired new length.
i
as the index where the next non-val
element should be placed.val
, place it at the index i
and increment i
.i
will be the new length of the array.Here’s the Python implementation based on the strategy:
def removeElement(nums, val):
i = 0
for j in range(len(nums)):
if nums[j] != val:
nums[i] = nums[j]
i += 1
return i
# Example usage:
nums = [3, 2, 2, 3]
val = 3
new_length = removeElement(nums, val)
print("New length:", new_length) # Output: 2
print("Modified array:", nums[:new_length]) # Output: [2, 2]
n
is the length of nums
. This is because we iterate through the list once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?