Remove Element
Remove Element is a easy arrays & hashing problem solved with the two pointer pattern.
The best approach, optimal (swap with the end), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (shift the rest left) up.
Problem
You are given an integer array nums and an integer val. Remove every copy of val from nums in place.
Return k, the number of elements that are not equal to val. After your function returns, the first k slots of nums must hold exactly those elements. They may be in any order, and whatever is left in the slots from k onward is ignored.
Do it without allocating another array: use only O(1) extra memory.
How your answer is checked: the judge reads nums after your function returns. It counts the elements of the input that are not val (call that k), and accepts the answer when the first k slots of nums, sorted, equal those elements sorted.
Examples
Example 1
- Input
nums = [5, 7, 5, 5, 9], val = 5- Output
2, nums = [7, 9, _, _, _]- Why
- Three copies of 5 are removed, so two values stay: 7 and 9. They must be in the first two slots, in any order; the slots after them are ignored.
Example 2
- Input
nums = [4, 1, 4, 0, 4, 2], val = 4- Output
3, nums = [1, 0, 2, _, _, _]- Why
- The kept values are 1, 0 and 2. Any order of them in the first three slots is accepted, for example [2, 1, 0, _, _, _].
Example 3
- Input
nums = [8, 8, 8], val = 8- Output
0, nums = [_, _, _]- Why
- Every element equals val, so nothing is kept and k is 0.
Constraints
0 <= nums.length <= 3 * 10^40 <= nums[i] <= 1000 <= val <= 100
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 29 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (shift the rest left) | O(n^2) | O(1) |
| Two pointers (copy the kept values forward) | O(n) | O(1) |
| Optimal (swap with the end) | O(n) | O(1) |
1Brute force (shift the rest left)
O(n^2)Each deletion can shift up to n elements, and there can be up to n deletions.O(1)Only the indexes i, j and the length n.Delete each copy of val the way you would in a plain array: shift every element after it one slot to the left, which covers the copy, and shrink the logical length n by one. Do not move i after a deletion, because a new value has just slid into slot i and it must be checked too. When i reaches n, the first n slots hold exactly the kept values, in their original order.
- Set n = nums.length and i = 0.
- While i < n: if nums[i] == val, copy nums[j + 1] into nums[j] for j from i to n - 2, then n--. Otherwise i++.
- Return n.
class Solution {
public int removeElement(int[] nums, int val) {
int n = nums.length;
int i = 0;
while (i < n) {
if (nums[i] == val) {
for (int j = i; j < n - 1; j++) {
nums[j] = nums[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
}class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
n = len(nums)
i = 0
while i < n:
if nums[i] == val:
for j in range(i, n - 1):
nums[j] = nums[j + 1]
n -= 1
else:
i += 1
return nclass Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
int i = 0;
while (i < n) {
if (nums[i] == val) {
for (int j = i; j < n - 1; j++) {
nums[j] = nums[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}
};function removeElement(nums, val) {
let n = nums.length;
let i = 0;
while (i < n) {
if (nums[i] === val) {
for (let j = i; j < n - 1; j++) {
nums[j] = nums[j + 1];
}
n--;
} else {
i++;
}
}
return n;
}2Two pointers (copy the kept values forward)
O(n)One pass over the array with O(1) work per element.O(1)Only the two indexes.Keep a write index k: the slots 0 to k - 1 already hold the values kept so far. A read index i scans the whole array once. When nums[i] is not val, copy it to nums[k] and move k on; when it is val, just skip it. The write index never passes the read index, so a value is never overwritten before it has been read. At the end the first k slots hold every kept value in its original order.
- Set k = 0.
- For i from 0 to nums.length - 1: if nums[i] != val, set nums[k] = nums[i] and k++.
- Return k.
class Solution {
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[k] = nums[i];
k++;
}
}
return k;
}
}class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
k = 0
for i in range(len(nums)):
if nums[i] != val:
nums[k] = nums[i]
k += 1
return kclass Solution {
public:
int removeElement(vector<int>& nums, int val) {
int k = 0;
for (int i = 0; i < (int) nums.size(); i++) {
if (nums[i] != val) {
nums[k] = nums[i];
k++;
}
}
return k;
}
};function removeElement(nums, val) {
let k = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== val) {
nums[k] = nums[i];
k++;
}
}
return k;
}3Optimal (swap with the end)
O(n)Every step either moves i right or shrinks n, and they start n apart, so there are at most n steps.O(1)Only i and n.Since the order of the kept values does not matter, a removed copy can be filled by any value that is still unchecked. Keep the live part of the array as nums[0 .. n - 1]. If nums[i] equals val, move the last live element nums[n - 1] into slot i and shrink n by one; do not move i, because the value that just arrived has not been checked yet. Otherwise nums[i] is kept, so move i on. When i meets n, the live part is exactly the kept values. This is still one pass, but it writes only once per removed value, which is much less work than the two-pointer copy when val is rare.
- Set i = 0 and n = nums.length.
- While i < n: if nums[i] == val, set nums[i] = nums[n - 1] and n--. Otherwise i++.
- Return n.
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
n--;
} else {
i++;
}
}
return n;
}
}class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
n = len(nums)
while i < n:
if nums[i] == val:
nums[i] = nums[n - 1]
n -= 1
else:
i += 1
return nclass Solution {
public:
int removeElement(vector<int>& nums, int val) {
int i = 0;
int n = nums.size();
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
n--;
} else {
i++;
}
}
return n;
}
};function removeElement(nums, val) {
let i = 0;
let n = nums.length;
while (i < n) {
if (nums[i] === val) {
nums[i] = nums[n - 1];
n--;
} else {
i++;
}
}
return n;
}Edge cases to test
- An empty array: return 0
- val does not appear at all: k is nums.length and the array may stay as it is
- Every element equals val: k is 0
- Copies of val only at the start, or only at the end
- A single element, equal to val or not
Hints
Hint 1
You do not have to delete anything. You only have to gather the values you keep in the front of the array and count them.
Hint 2
Use a write index k for the next free slot of the front part. Scan the array and copy every value that is not val to nums[k], then move k on.
Hint 3
The order of the kept values does not matter. When nums[i] == val you can overwrite it with the last element and shrink the array by one, which writes only once per removed value.
FAQ
What is the best time complexity for Remove Element?
Optimal (swap with the end) runs in O(n) time and O(1) extra space. Every step either moves i right or shrinks n, and they start n apart, so there are at most n steps.
Which pattern does Remove Element use?
It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Two Sum II - Input Array Is Sorted, Valid Triangle Number, Container With Most Water.
Is there a brute force solution for Remove Element?
Yes. Brute force (shift the rest left) takes O(n^2) time and O(1) space. Delete each copy of val the way you would in a plain array: shift every element after it one slot to the left, which covers the copy, and shrink the logical length n by one.
Which edge cases should I test for Remove Element?
An empty array: return 0; val does not appear at all: k is nums.length and the array may stay as it is; Every element equals val: k is 0; Copies of val only at the start, or only at the end; A single element, equal to val or not.