Remove Element LeetCode Solution

Last updated on February 22nd, 2024 at 03:26 am

Here, We see Remove Element problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Remove Element LeetCode Solution

Remove Element LeetCode Solution

Problem Statement

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
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 k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).

Remove Element Leetcode Solution C++

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
		int length = nums.size(), index = 0;
		while ( index < length )
		{
			 if ( nums[index] == val )
			 {
				 nums[index] = nums[length - 1];
				 -- length;
			 }
			else ++index;
		}
		 return length;         
    }
};
Code language: C++ (cpp)

Remove Element Leetcode Solution Java

class Solution {
    public int removeElement(int[] nums, int val) {
    int l = nums.length;
    for (int i=0; i<l; i++) {
        if (nums[i] == val) {
            nums[i--] = nums[l-- -1];
        }
    }
    return l;        
    }
}
Code language: Java (java)

Remove Element Leetcode Solution JavaScript

var removeElement = function(nums, val) {
    let left = 0;
    let right = nums.length - 1;
    
    while (left <= right) {
        if (nums[left] === val) {
            nums[left] = nums[right];
            right--;
        }
        else {
            left++;
        }
    }
    return left;    
};
Code language: JavaScript (javascript)

Remove Element Leetcode Solution Python

class Solution(object):
    def removeElement(self, nums, val):
        start, end = 0, len(nums) - 1
        while start <= end:
            if nums[start] == val:
                nums[start], nums[end], end = nums[end], nums[start], end - 1
            else:
                start +=1
        return start
Code language: Python (python)
Scroll to Top