Remove Element (LeetCode 27): Solution and Explanation

Easy
Array
Two Pointers

Given an array and a value, remove every occurrence of that value in place and return how many elements remain. The kept elements must occupy the front of the array, in any order, and whatever sits after them does not matter.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

If extra memory were allowed, you would build a new list containing every element not equal to val and copy it back. The in-place requirement rules that out, and actually deleting elements from the middle of an array is no better, because each deletion shifts everything after it and the total cost becomes O(n²) when many elements match.

The key observation is that you never need to delete anything. The problem only checks the first k positions, so all you need is to make sure those positions hold the kept elements. Picture two fingers on the array. One finger, the reader, walks over every element. The other, the writer, points at the next slot in the kept prefix. Whenever the reader sees a value worth keeping, you copy it to the writer's slot and move the writer forward. Values equal to val are simply skipped, and they get overwritten later or end up beyond position k.

The writer can never pass the reader, because it only advances when the reader does, so the copy never destroys an element you have not looked at yet. When the reader finishes, the writer's position is exactly the number of kept elements. This read and write pointer pattern shows up again in Remove Duplicates from Sorted Array and Move Zeroes, so it is worth internalizing here.

Approach: Read and write pointers

  1. Initialize the write index k to 0. It marks where the next kept element should go.
  2. Loop i over every index of nums; this is the read pointer.
  3. If nums[i] != val, copy it to nums[k] and increment k.
  4. If nums[i] == val, do nothing, so the element is effectively dropped.
  5. After the loop, return k. The first k slots hold every element that is not val, in their original relative order.

Step-by-step example

nums = [3, 2, 2, 3], val = 3
  1. Start with k = 0. At i = 0, nums[0] is 3, which equals val, so it is skipped and k stays 0.
  2. At i = 1, nums[1] is 2. Copy it to nums[0], giving [2, 2, 2, 3], and set k = 1.
  3. At i = 2, nums[2] is 2. Copy it to nums[1], leaving [2, 2, 2, 3], and set k = 2.
  4. At i = 3, nums[3] is 3, so it is skipped.
  5. The loop ends and the function returns 2. The first two slots are [2, 2], which is the expected result.

Code: Python, Java, C++

1class Solution:
2    def removeElement(self, nums: List[int], val: int) -> int:
3        k = 0
4        for i in range(len(nums)):
5            if nums[i] != val:
6                nums[k] = nums[i]
7                k += 1
8        return k

Time and space complexity

Time

O(n)

The read pointer visits each of the n elements exactly once, and each visit does at most one comparison and one assignment.

Space

O(1)

The array is modified in place and only two integer indices are used, regardless of input size.

Other approaches

Swap with the last element (time O(n), space O(1))

Keep i at the front and n as the logical length. When nums[i] == val, overwrite it with nums[n - 1] and shrink n without advancing i; otherwise advance i. This does fewer writes when matches are rare, which matters if writes are expensive, but it does not preserve the order of kept elements.

Build a filtered copy (time O(n), space O(n))

Create a new list of the kept elements and copy it into the front of nums. It is easy to reason about but breaks the in-place rule by using O(n) extra memory.

Common mistakes

  • Calling remove or pop inside a loop. Each removal shifts the remaining elements, which makes the solution quadratic and also skips elements when you iterate by index.
  • Returning the length of the whole array instead of k. The judge only reads the first k entries, so the return value is what defines the answer.
  • In the swap variant, advancing i after swapping in the last element. The swapped-in value might also equal val and needs to be checked.
  • Assuming the tail must be cleared. Values after index k - 1 are ignored, so writing zeros or deleting them is wasted work.

Frequently asked questions

Why does Remove Element return a number instead of a new array?

The array is modified in place, so the caller already has it. The returned count tells the caller how many leading elements are valid, and the rest of the array is treated as garbage.

Does the order of the remaining elements matter?

No, any order is accepted. The read and write pointer method happens to keep the original order, while the swap-with-last method does not, and both are valid.

Is this the same technique as Move Zeroes?

Very close. Move Zeroes uses the same write pointer to compact the non-zero values, then fills the tail with zeros or swaps instead of copying so the zeros end up at the back.