DEV Community

Debesh P.
Debesh P.

Posted on • Edited on

27. Remove Element | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/remove-element/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/remove-element/solutions/7439481/most-optimal-solution-beats-500-best-eas-hegz


leetcode 27


Problem in Simple Words

You are given an integer array nums and an integer val.

  • Remove all occurrences of val from the array
  • Do the operation in place
  • Order of elements does not matter
  • Return the number of elements that are not equal to val

What the Problem Is Really Asking

You are not asked to resize the array.

You are only asked to:

  • Rearrange the array so that all elements not equal to val come first
  • Return how many such elements exist

Everything beyond that index does not matter.


Key Idea

We use two pointers:

  • i → scans every element
  • j → tracks where the next valid element should go

Whenever we see a value that is not equal to val, we keep it.


Why This Works

  • We overwrite only values that are meant to be removed
  • All valid elements are packed at the front
  • No extra memory is used

Variables Explained

int j = 0;
Enter fullscreen mode Exit fullscreen mode
  • j stores the position where the next valid element should be placed
  • It also ends up being the final count of valid elements

Step-by-Step Logic

We loop through the array:

for (int i = 0; i < n; i++) {
Enter fullscreen mode Exit fullscreen mode

For every element:

  • If it is not equal to val

    • Copy it to index j
    • Increment j
  • If it equals val

    • Skip it

Full Code

class Solution {
    public int removeElement(int[] nums, int val) {
        int n = nums.length;
        int j = 0;

        for (int i = 0; i < n; i++) {
            if (nums[i] != val) {
                nums[j] = nums[i];
                j++;
            }
        }

        return j;
    }
}
Enter fullscreen mode Exit fullscreen mode

Example Walkthrough

Input:

nums = [3,2,2,3]
val = 3
Enter fullscreen mode Exit fullscreen mode

Step by step:

  • i = 0 → value is 3 → skip
  • i = 1 → value is 2 → keep → nums[0] = 2
  • i = 2 → value is 2 → keep → nums[1] = 2
  • i = 3 → value is 3 → skip

Result:

  • First 2 elements are valid
  • Returned value = 2

Why We Return j

  • j counts how many valid elements were placed
  • It represents the new length of the array
  • Everything after index j - 1 can be ignored

Time and Space Complexity

  • Time: O(n)
  • Space: O(1)

Final Takeaway

This problem is about filtering, not deleting.

Once you realize that the array does not need to shrink,
just be rearranged, the solution becomes straightforward and efficient.

Top comments (0)