15% off all plans & roadmaps Use code
See plansRemove Element
- LeetCode 27
- Easy
- Two Pointers
- In-place Array Modification
Updated
TL;DR: Remove every copy of a value from an array in place, then return how many values remain. The winning idea is a writer index that copies each kept value forward in one pass.
Problem
Given an integer array nums and an integer val, remove every occurrence of val from nums in place. The order of the remaining elements may change. Then return the number of elements in nums that are not equal to val.
Call that count k. To be accepted, you must do the following:
- Rearrange
numsso the firstkelements are the values that are not equal toval. The rest of the array does not matter, and neither does its original size. - Return
k.
The judge calls your function and checks that the returned value equals the expected count. It then sorts the first k elements and compares them with the expected values. If every check passes, the solution is accepted.
Example 1
Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2,_,_] Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k.
Example 2
Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. The five elements can be returned in any order. It does not matter what you leave beyond the returned k.
Constraints
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100
Constraints that matter
nums.lengthis at most 100, so an O(n^2) shift passes the limit. The interview bar still expects one linear pass, because the shift cost grows with the square of the length.- The problem requires in-place edits, so the first
kcells must hold the kept values. Building a separate list breaks that rule, even though it returns the right count. nums[i]is at most 50 andvalcan be up to 100.valmay never appear, sokcan equal the length of the array.- Length 0 is allowed. Any code that reads
nums[0]before checking the length will fail on that input.
Hints
Hint 1
The output is a prefix of the array, and the order of the kept values does not matter.
Hint 2
Scan the array from the left.
Solution
Intuition
The output is a prefix of the array, and the order of the kept values does not matter. That means you never need to delete anything. You only need to decide which values survive and copy them to the front.
Picture a line of people where some must step out. The writer is the next open spot at the front, and the reader walks the line, moving each staying person into that spot.
This is the two pointers pattern with in-place array modification. One index, the reader, visits every value exactly once. A second index, the writer, marks the next free slot at the front of the array.
Each kept value is copied to the writer's slot. The writer never gets ahead of the reader, so a copy never overwrites a value you have not read yet. When the reader finishes, the writer equals the count of kept values.
Worked example
Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2 Output: 5 Explanation: Three copies of 2 are removed. The kept values, in reading order, are 0, 1, 3, 0, 4, so the function returns 5. The first five cells then hold those values. Sorting the same five values gives 0, 0, 1, 3, 4, which is the form the judge compares against.
Approach 1: Brute force: shift left
Scan the array from the left. Each time you hit val, shift every later element one slot to the left and shrink the length. Then look at the same index again, because a new value has moved into it.
This works, but each removal moves the whole tail. A value that appears many times pays that cost many times over.
Steps
- Set
nto the array length andito 0. - While
iis less thann, readA[i]. - If
A[i]equalselem, copy each element afterione slot left, then decreasenby 1. Do not advancei. - Otherwise, increase
iby 1. - Return
n.
Dry run
Start with [0, 1, 2, 2, 3, 0, 4, 2], n = 8, elem = 2.
- i = 2 holds 2. Shift the tail left:
[0, 1, 2, 3, 0, 4, 2, 2], n = 7. - i = 2 holds 2 again. Shift the tail left:
[0, 1, 3, 0, 4, 2, 2, 2], n = 6. - i = 2 holds 3, i = 3 holds 0, i = 4 holds 4. Advance past each one.
- i = 5 holds 2. Nothing sits after it to shift, so n becomes 5.
- i = 5 is no longer below n, so the loop stops. Return 5. The first five cells are 0, 1, 3, 0, 4.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the length of the array. Each removal shifts at most n - 1 elements, and there are at most n removals, so the shifts cost at most n times (n - 1) steps. The scan adds n more steps, so the total is O(n^2). The only extra state is a few integers, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def removeElement(self, A: List[int], elem: int) -> int:
n = len(A)
i = 0
while i < n:
if A[i] == elem:
# shift the tail one slot left
for j in range(i, n - 1):
A[j] = A[j + 1]
n -= 1
else:
i += 1
return nJavaTested in our runner
class Solution {
public int removeElement(int[] A, int elem) {
int n = A.length;
int i = 0;
while (i < n) {
if (A[i] == elem) {
// shift the tail one slot left
for (int j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int removeElement(vector<int>& A, int elem) {
int n = A.size();
int i = 0;
while (i < n) {
if (A[i] == elem) {
// shift the tail one slot left
for (int j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
};JavaScriptTested in our runner
/**
* @param {number[]} A
* @param {number} elem
* @return {number}
*/
var removeElement = function(A, elem) {
let n = A.length;
let i = 0;
while (i < n) {
if (A[i] === elem) {
// shift the tail one slot left
for (let j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
};GoTested in our runner
func removeElement(A []int, elem int) int {
n := len(A)
i := 0
for i < n {
if A[i] == elem {
// shift the tail one slot left
for j := i; j < n-1; j++ {
A[j] = A[j+1]
}
n--
} else {
i++
}
}
return n
}C#Tested in our runner
public class Solution {
public int removeElement(int[] A, int elem) {
int n = A.Length;
int i = 0;
while (i < n) {
if (A[i] == elem) {
// shift the tail one slot left
for (int j = i; j < n - 1; j++) {
A[j] = A[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
}Approach 2: Sort, then block removal
What is slow in the brute force is that every removed copy pays for a full shift. Sorting puts all copies of val into one contiguous block. One copy of the tail then removes the whole block at once.
Sorting changes the order of the values, which the problem allows. The block is found with two linear scans after the sort.
Steps
- Sort
Ain ascending order. - Scan from the left to find
lo, the first index whose value is not less thanelem. - From
lo, advance while the values equalelem. The stopping index ishi, the first cell after the block. - Copy
A[hi]throughA[n - 1]into the slots starting atlo, one at a time. - Return
lo + (n - hi), the number of slots written.
Dry run
Sorted array: [0, 0, 1, 2, 2, 2, 3, 4], elem = 2, n = 8.
- The scan for
lostops at index 3, the first 2. So lo = 3. - The scan for
himoves past indexes 3, 4, 5. So hi = 6. - Copy A[6] = 3 into slot 3. The array becomes
[0, 0, 1, 3, 2, 2, 3, 4]. - Copy A[7] = 4 into slot 4. The array becomes
[0, 0, 1, 3, 4, 2, 3, 4]. - Return lo + (n - hi) = 3 + 2 = 5. The first five cells are 0, 0, 1, 3, 4.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(1) extra beyond the sort. The sort itself uses O(log n) to O(n) internal memory, depending on the language. |
Let n be the length of the array. A comparison sort takes O(n log n) time. The scans for lo and hi each visit at most n cells, and the tail copy writes at most n cells, so those steps add only O(n). The total time is O(n log n). Beyond the sort, the scans and copy use a few integers of their own.
PythonTested in our runner
from typing import List, Optional
class Solution:
def removeElement(self, A: List[int], elem: int) -> int:
A.sort()
n = len(A)
# lo is the first index holding a value not less than elem
lo = 0
while lo < n and A[lo] < elem:
lo += 1
# hi is the first index after the block of elem values
hi = lo
while hi < n and A[hi] == elem:
hi += 1
# copy the tail into the slots that start at lo
k = lo
for i in range(hi, n):
A[k] = A[i]
k += 1
return kJavaTested in our runner
import java.util.*;
class Solution {
public int removeElement(int[] A, int elem) {
Arrays.sort(A);
int n = A.length;
// lo is the first index holding a value not less than elem
int lo = 0;
while (lo < n && A[lo] < elem) lo++;
// hi is the first index after the block of elem values
int hi = lo;
while (hi < n && A[hi] == elem) hi++;
// copy the tail into the slots that start at lo
int k = lo;
for (int i = hi; i < n; i++) {
A[k++] = A[i];
}
return k;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int removeElement(vector<int>& A, int elem) {
sort(A.begin(), A.end());
int n = A.size();
// lo is the first index holding a value not less than elem
int lo = 0;
while (lo < n && A[lo] < elem) lo++;
// hi is the first index after the block of elem values
int hi = lo;
while (hi < n && A[hi] == elem) hi++;
// copy the tail into the slots that start at lo
int k = lo;
for (int i = hi; i < n; i++) A[k++] = A[i];
return k;
}
};JavaScriptTested in our runner
/**
* @param {number[]} A
* @param {number} elem
* @return {number}
*/
var removeElement = function(A, elem) {
A.sort((a, b) => a - b);
const n = A.length;
// lo is the first index holding a value not less than elem
let lo = 0;
while (lo < n && A[lo] < elem) lo++;
// hi is the first index after the block of elem values
let hi = lo;
while (hi < n && A[hi] === elem) hi++;
// copy the tail into the slots that start at lo
let k = lo;
for (let i = hi; i < n; i++) {
A[k] = A[i];
k++;
}
return k;
};GoTested in our runner
import "sort"
func removeElement(A []int, elem int) int {
sort.Ints(A)
n := len(A)
// lo is the first index holding a value not less than elem
lo := 0
for lo < n && A[lo] < elem {
lo++
}
// hi is the first index after the block of elem values
hi := lo
for hi < n && A[hi] == elem {
hi++
}
// copy the tail into the slots that start at lo
k := lo
for i := hi; i < n; i++ {
A[k] = A[i]
k++
}
return k
}C#Tested in our runner
public class Solution {
public int removeElement(int[] A, int elem) {
Array.Sort(A);
int n = A.Length;
// lo is the first index holding a value not less than elem
int lo = 0;
while (lo < n && A[lo] < elem) lo++;
// hi is the first index after the block of elem values
int hi = lo;
while (hi < n && A[hi] == elem) hi++;
// copy the tail into the slots that start at lo
int k = lo;
for (int i = hi; i < n; i++) {
A[k] = A[i];
k++;
}
return k;
}
}The In-place Array Modification infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
In-place Array Modification
Part of Two Pointers
Approach 3: One-pass two pointers (writer and reader)OptimalIn-place Array Modification
What is slow in the sort is that it does more work than the task needs. The output only needs the kept values at the front, in any order, so reordering values the answer never uses is wasted effort.
A reader scans once and copies each kept value to the writer's slot. Each cell is read and written a constant number of times, so one pass is enough.
Steps
- Set
writerto 0. - Move
readerfrom 0 to n - 1. - If
A[reader]is notelem, copy it toA[writer]. - Increase
writerby 1 only after a copy. - Return
writer.
Dry run
Start with [0, 1, 2, 2, 3, 0, 4, 2], elem = 2, writer = 0.
| Step | reader | A[reader] | action | writer after step | array after step |
|---|---|---|---|---|---|
| 1 | 0 | 0 | copy to slot 0 | 1 | [0, 1, 2, 2, 3, 0, 4, 2] |
| 2 | 1 | 1 | copy to slot 1 | 2 | [0, 1, 2, 2, 3, 0, 4, 2] |
| 3 | 2 | 2 | skip | 2 | [0, 1, 2, 2, 3, 0, 4, 2] |
| 4 | 3 | 2 | skip | 2 | [0, 1, 2, 2, 3, 0, 4, 2] |
| 5 | 4 | 3 | copy to slot 2 | 3 | [0, 1, 3, 2, 3, 0, 4, 2] |
| 6 | 5 | 0 | copy to slot 3 | 4 | [0, 1, 3, 0, 3, 0, 4, 2] |
| 7 | 6 | 4 | copy to slot 4 | 5 | [0, 1, 3, 0, 4, 0, 4, 2] |
| 8 | 7 | 2 | skip | 5 | [0, 1, 3, 0, 4, 0, 4, 2] |
The loop ends with writer = 5. Return 5. The first five cells are 0, 1, 3, 0, 4, which holds every kept value.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of the array. The reader loop runs n times, and each iteration does one comparison and at most one copy, so the time is O(n). Since the writer is never ahead of the reader, each write lands on a cell that has already been read. The only extra state is two integers, so the space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def removeElement(self, A: List[int], elem: int) -> int:
writer = 0
for reader in range(len(A)):
# keep every value that is not elem
if A[reader] != elem:
A[writer] = A[reader]
writer += 1
return writerJavaTested in our runner
class Solution {
public int removeElement(int[] A, int elem) {
int writer = 0;
for (int reader = 0; reader < A.length; reader++) {
// keep every value that is not elem
if (A[reader] != elem) {
A[writer++] = A[reader];
}
}
return writer;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int removeElement(vector<int>& A, int elem) {
int writer = 0;
int n = A.size();
for (int reader = 0; reader < n; reader++) {
// keep every value that is not elem
if (A[reader] != elem) {
A[writer] = A[reader];
writer++;
}
}
return writer;
}
};JavaScriptTested in our runner
/**
* @param {number[]} A
* @param {number} elem
* @return {number}
*/
var removeElement = function(A, elem) {
let writer = 0;
for (let reader = 0; reader < A.length; reader++) {
// keep every value that is not elem
if (A[reader] !== elem) {
A[writer] = A[reader];
writer++;
}
}
return writer;
};GoTested in our runner
func removeElement(A []int, elem int) int {
writer := 0
for reader := 0; reader < len(A); reader++ {
// keep every value that is not elem
if A[reader] != elem {
A[writer] = A[reader]
writer++
}
}
return writer
}C#Tested in our runner
public class Solution {
public int removeElement(int[] A, int elem) {
int writer = 0;
for (int reader = 0; reader < A.Length; reader++) {
// keep every value that is not elem
if (A[reader] != elem) {
A[writer] = A[reader];
writer++;
}
}
return writer;
}
}Common mistakes
writer += 1placed outside theif. Every index advances, so kept values leave gaps and the count is wrong. Increasewriteronly inside the branch that copies a value.if A[reader] != A[writer]in place ofif A[reader] != elem. The check compares two array cells instead of the target value. Compare the current value withelem.return readerorreturn len(A)at the end. Both return the original length. Returnwriter, which counts the kept values.A.remove(elem)orA.pop(i)inside a loop overA. Each call shifts the tail, which costs O(n), and the loop skips the value that moved into the current index. Use the writer pointer instead.nums = [x for x in nums if x != val]in Python. This rebinds the local name to a new list, so the caller's list does not change. Write into the same list, or use slice assignment such asnums[:] = ....
Edge cases
- Empty array
[]with anyval. The answer is 0, and the code must not touch index 0. - Every value equals
val, such as[4, 4, 4]withval = 4. The answer is 0, and the array content beyondkdoes not matter. - No value equals
val, such as[1, 2, 3]withval = 9. The answer is 3, and the array is unchanged. - The only match is the last cell, such as
[1, 2, 3]withval = 3. The answer is 2, and the first two cells hold 1 and 2. - Kept values repeat, such as
[2, 2, 3, 2]withval = 3. The answer is 3, and the first three cells hold 2, 2, 2. A solution that compares with the previous kept value would wrongly drop repeats here.
Follow-ups interviewers ask
- What if the kept values must keep their original relative order?
- The writer solution already keeps the order. The writer copies values from left to right and never passes the reader, so each kept value lands in the same relative position among the kept values.
- What if removals are rare and you want fewer writes?
- Use two indexes from the ends. Keep
iat the front andendat the back. WhenA[i]equalselem, copyA[end - 1]intoA[i]and decreaseend, without advancingi. Each removal costs one write, and the loop still runs O(n) times. The order of the kept values changes, which the problem allows. - What if the array is already sorted?
- The copies of
valform one block, so you can find its two ends with binary search in O(log n) time. The tail still has to move left to fill the gap, so the copy costs O(n) time in the worst case. Binary search speeds up finding the block, but it does not remove the need to move the tail.
Remove Element FAQ
What is the time complexity of Remove Element?
The two pointers solution runs in O(n) time, because the reader visits each index once. The shift brute force runs in O(n^2) time, because each removal moves the tail of the array.
Why use two pointers for Remove Element?
Two pointers separate reading from writing. The reader finds each value to keep, and the writer marks the slot where that value belongs. One pass is enough, so no value needs to be examined twice.
Can Remove Element be solved in O(1) extra space?
Yes. The writer solution uses two integers and writes into the input array, so the extra space is O(1). The sort-based approach needs internal memory for the sort, which is O(log n) to O(n) in some languages.
Does Remove Element need to keep the original order?
No. The problem allows any order for the first k elements. The writer solution keeps the order anyway, because it copies values from left to right.
Why does my Python solution pass the example but the judge says the array is wrong?
You may have built a new list and returned its length. The judge reads the original list, so the first k cells must be changed in place. Write into nums directly or use slice assignment such as nums[:] = ....
Asked at
See which companies ask this — Pro
Related problems
- Remove Duplicates from Sorted Array · same technique: In-place Array Modification
- Merge Strings Alternately · same technique: In-place Array Modification
- Move Zeroes · same technique: In-place Array Modification
- Intersection of Two Arrays · same technique: In-place Array Modification
- Sort Array By Parity · same technique: In-place Array Modification
- Sort Colors · next harder, same pattern
- Happy Number · same pattern: Two Pointers
- Linked List Cycle · same pattern: Two Pointers
- Reverse String · same pattern: Two Pointers
- Squares of a Sorted Array · same pattern: Two Pointers