Magicsheet logo

Remove Element

Easy
48.3%
Updated 6/1/2025

Remove Element

What is this problem about?

The Remove Element interview question asks you to remove all occurrences of a given value from an array in-place and return the new length. The order of elements not equal to the target value does not need to be preserved in a specific way, and elements beyond the returned length do not matter. No extra space is allowed.

Why is this asked in interviews?

This problem is asked at Apple, Uber, Microsoft, Meta, Amazon, and Google as a fundamental in-place array manipulation exercise. It is the simplest application of the two-pointer technique and is often used as an icebreaker in array-focused interviews. It validates that a candidate understands in-place modification and can handle the pointer logic cleanly, even for edge cases like all elements being the target value.

Algorithmic pattern used

The pattern is the two-pointer technique. Use a write pointer k starting at 0. Scan through the array with a read pointer i. Whenever nums[i] is not equal to the target value, copy it to nums[k] and increment k. At the end, k is the new length. This is O(n) time and O(1) space.

Example explanation

Array: [3, 2, 2, 3], target = 3.

  • i=0: nums[0]=3 equals target → skip.
  • i=1: nums[1]=2 ≠ target → nums[k=0]=2, k=1.
  • i=2: nums[2]=2 ≠ target → nums[k=1]=2, k=2.
  • i=3: nums[3]=3 equals target → skip.

New length: 2. Array begins with [2, 2, ...].

An alternative when order doesn't matter: swap the target element with the last unprocessed element and shrink the array from the right, which minimizes writes.

Common mistakes candidates make

  • Forgetting to return k (or returning k-1 due to off-by-one errors).
  • Deleting elements by shifting all subsequent elements left — this is O(n^2) and unnecessary.
  • Handling an empty array incorrectly — always check for length 0 first.
  • Confusing this problem with removing ALL elements (return 0) when the array is entirely the target value.

Interview preparation tip

For the Remove Element coding problem, the two-pointer array interview pattern is your go-to. Practice both the standard version (stable relative order) and the swap-from-end version (minimizes writes). Interviewers at Yahoo and Accenture may ask which variant is more efficient in different scenarios — the swap version is better when the target value is rare. Being able to discuss both approaches shows a well-rounded understanding.

Similar Questions