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
Examples
Example 1:
1 2 3 4 5 6 7 | Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2] Explanation: Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted. |
Example 2:
1 2 3 4 5 6 | Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3] Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. |
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
1 2 3 4 5 6 7 8 9 10 | class Solution { public int removeElement(int[] nums, int val) { int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) nums[index++] = nums[i]; } return index; } } |
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 🙂