Remove Element

Easyarraytwo-pointers
Category: Array & Hashing
Companies that ask this question:
AmazonGoogleMicrosoft

Approach

Remove Element

Approach

Use two pointers to overwrite elements in place.

Algorithm

  1. Initialize write pointer k at 0
  2. For each element:
    • If not equal to val: copy to position k, increment k
    • If equal to val: skip
  3. Return k (new length)

Complexity

  • Time: O(n) - single pass
  • Space: O(1) - in-place

Key Insights

  • Two-pointer technique for in-place removal
  • No need to preserve order beyond first k elements
  • Similar to partition algorithm

Solution

java
1class Solution {
2    public int removeElement(int[] nums, int val) {
3        int k = 0;
4        
5        for (int i = 0; i < nums.length; i++) {
6            if (nums[i] != val) {
7                nums[k] = nums[i];
8                k++;
9            }
10        }
11        
12        return k;
13    }
14}
Loading visualizer...