# Leetcode 27: Remove Element

Category: Easy

## Problem

Given an array nums and a value `val`, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with `O(1)` extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

https://leetcode.com/problems/remove-element

## Solution Approach

In this problem of ‘Remove Element’, we have to remove the elements in place and then return the size of the array after the removal. The condition is that we do not have to use any extra space.

This problem can be solved by utilizing two pointers. The first will loop through the array and the second is where we insert the target value. (i.e value which is not in the ‘Val’ variable). The second pointer will ignore the target values. It will move when non-target values are encountered. Whenever we find non-target values we will insert them in place of the target variable values in the array. The second variable will be returned as the answer because it stores the number of non-target array elements.

As we are looping through the array only once, hence our time complexity will be O(n). No extra space is required, therefore the space complexity is O(1).

Coming to the code, of the same it’s pretty straightforward. We will initialize a variable (let’s call it index) with 0. Then we loop through the array with ‘i’ as an iterator. Whenever we find an array element that is not our targeted ‘Val’ value, then we will change the array element at the index to that value. In the end, we will return the index as the answer.

## Solution code

For more Leetcode explained solutions visit Leetcode Solutions.

If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via the Contact page I will surely respond. Happy Leetcoding ðŸ™‚