Remove Element LeetCode Solution

Last updated on January 20th, 2025 at 10:50 pm

Here, we see a Remove Element LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Array, Two-Pointers

Level of Question

Easy

Remove Element LeetCode Solution

Remove Element LeetCode Solution

1. 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)

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is Two Pointers. This pattern is commonly used when we need to process elements from both ends of a collection (or array) or when we need to modify the array in-place while maintaining a specific condition. Here, one pointer (indexleft, or start) iterates through the array, and the other pointer (lengthright, or end) tracks the valid portion of the array.

3. Code Implementation in Different Languages

3.1 Remove Element C++

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

3.2 Remove Element 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;        
    }
}

3.3 Remove Element 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;    
};

3.4 Remove Element 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

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n)O(1)
JavaO(n)O(1)
JavaScriptO(n)O(1)
PythonO(n)O(1)
  • The algorithm is efficient because it avoids shifting elements in the array when a match is found. Instead, it swaps the matched element with the last valid element.
  • The order of elements in the array is not preserved, as the algorithm focuses on minimizing operations rather than maintaining order.
  • The returned value is the new length of the array, and the first length elements of the array contain the valid elements after removal.
Scroll to Top