Unlike solutions with swapping elements this one does as little swaps as possible.

```
def remove_element(nums, val)
l = 0
r = nums.size - 1
while l <= r
if nums[r] == val
r -= 1
elsif nums[l] == val
nums[l] = nums[r]
l += 1
r -= 1
else
l += 1
end
end
r + 1
end
```