LeetCode 27. Remove Element | Two Pointers Solution in JavaScript

📌 Introduction
In this post, we’ll solve LeetCode 27. Remove Element. We’ll cover the two-pointer approach, and analyze the time and space complexities. Code examples will be in JavaScript, with step-by-step explanations.
👉 Original problem link: LeetCode – Remove Element
1. Problem Overview
The task is to modify an array nums
in-place by removing all occurrences of a specific integer val
. The relative order of the remaining elements can be changed. After the removal, the function should return the count of elements that are not equal to val
. These valid elements must occupy the beginning of the array. The content of the array beyond this point is irrelevant.
2. Example
Input: nums = [3,2,2,3]
, val = 3
Output: 2
, nums = [2,2,_,_]
Explanation: The function should return k = 2
, with the first two elements of nums
being 2
. The values beyond the returned length k
do not matter.
3. Approaches
🔹 Optimized Approach
Use a two-pointer technique with
start
at the beginning andend
at the end of the array.If the element at
start
is the target value, swap it with the element atend
and decrementend
.If the element at
start
is not the target, simply incrementstart
.Continue this process until the pointers cross.
The final value of
start
will be the count of elements not equal toval
.
Code (JavaScript):
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let start = 0, end = nums.length - 1
while(start <= end){
if(nums[start] == val){ //if we find target number, push to back by swapping with last element
[nums[start], nums[end]] = [nums[end], nums[start]]
end--
} else {
start++
}
}
return start
};
Time Complexity = O(N)
Space Complexity = O(1)
4. Key Takeaways
✨ Two-pointer approaches are powerful for in-place array manipulation problems.
✨ By swapping unwanted elements with those at the end of the array, we can achieve the desired result in a single pass.
✨ This technique avoids creating a new array, optimizing space complexity to O(1).
Subscribe to my newsletter
Read articles from Shanks directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Shanks
Shanks
Senior Dev trying to crack FAANG | Sharing the grind, growth, and late-night code sessions