Skip to main content

Command Palette

Search for a command to run...

LeetCode 27. Remove Element | Two Pointers Solution in JavaScript

Published
•2 min read•View as Markdown
S

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

📌 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 and end at the end of the array.

  • If the element at start is the target value, swap it with the element at end and decrement end.

  • If the element at start is not the target, simply increment start.

  • Continue this process until the pointers cross.

  • The final value of start will be the count of elements not equal to val.

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

More from this blog

Code With Shanks

12 posts

Senior Dev on the FAANG quest – documenting the hustle of daily DSA practice, growth through setbacks. Sharing code insights, problem solutions & lessons learned.