Remove Element (LeetCode 27): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Initialize the write index
kto 0. It marks where the next kept element should go. - Loop
iover every index ofnums; this is the read pointer. - If
nums[i] != val, copy it tonums[k]and incrementk. - If
nums[i] == val, do nothing, so the element is effectively dropped. - After the loop, return
k. The firstkslots hold every element that is notval, in their original relative order.
Step-by-step example
nums = [3, 2, 2, 3], val = 3
- Start with
k = 0. Ati = 0,nums[0]is 3, which equalsval, so it is skipped andkstays 0. - At
i = 1,nums[1]is 2. Copy it tonums[0], giving [2, 2, 2, 3], and setk = 1. - At
i = 2,nums[2]is 2. Copy it tonums[1], leaving [2, 2, 2, 3], and setk = 2. - At
i = 3,nums[3]is 3, so it is skipped. - 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 k1class Solution {
2 public int removeElement(int[] nums, int val) {
3 int k = 0;
4 for (int i = 0; i < nums.length; i++) {
5 if (nums[i] != val) {
6 nums[k] = nums[i];
7 k++;
8 }
9 }
10 return k;
11 }
12}1class Solution {
2public:
3 int removeElement(vector<int>& nums, int val) {
4 int k = 0;
5 for (int i = 0; i < nums.size(); i++) {
6 if (nums[i] != val) {
7 nums[k] = nums[i];
8 k++;
9 }
10 }
11 return k;
12 }
13};Time and space complexity
O(n)
The read pointer visits each of the n elements exactly once, and each visit does at most one comparison and one assignment.
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
removeorpopinside 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 firstkentries, so the return value is what defines the answer. - In the swap variant, advancing
iafter swapping in the last element. The swapped-in value might also equalvaland needs to be checked. - Assuming the tail must be cleared. Values after index
k - 1are 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.