Remove Element solution and explanation
9 more videos on this problem
Remove Element - Leetcode 27 - PythonNeetCode · 9:05 · 169K views
Remove Element | Leetcode problem 27Technosage · 6:30 · 73K views
LeetCode Remove Element Solution Explained - JavaNick White · 6:21 · 40K views
Remove Element - LeetCode #27 - Python, JavaScript, Java, C++CodingNinja · 4:32 · 24K views
LeetCode 27 | REMOVE ELEMENT | ARRAYS | C++ [ Approach and Code Explanation]Krishna Teaches · 6:19 · 19K views
Remove Element - Leetcode 27 - 2 Pointers (Python)Greg Hogg · 4:56 · 15K views
LeetCode 27: Remove ElementAbstracted Away · 3:16 · 14K views
Leetcode | 27. Remove Element | Easy | Java SolutionDeveloper Docs · 4:58 · 9K views
LeetCode Solution - 27. Remove Element | Microsoft InterviewThinkFWD · 11:41 · 6K views
Leetcode 27 – Remove Element - TWO POINTERSTiCungBim DSA · 16:18 · 5K views
The problem
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
- Change the array
numssuch that the firstkelements ofnumscontain the elements which are not equal toval. The remaining elements ofnumsare not important as well as the size ofnums. - Return
k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be 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 (hence they are underscores).
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. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100
Approach overview
Problem Overview: You are given an integer array nums and a value val. Remove all occurrences of val in-place and return the number of remaining elements. The array must be modified without allocating extra space, so the solution relies on careful index movement rather than creating a new array.
Approach 1: Two-Pointer (Overwrite) Technique (Time: O(n), Space: O(1))
This method scans the array once while maintaining a write index for valid elements. Iterate through the array using a read pointer. Every time you see a number that is not equal to val, copy it to the write pointer and move the write pointer forward. Elements equal to val are skipped, effectively overwriting them with valid elements encountered later. The key insight: the write pointer always marks the next position where a non-val element should go.
This preserves the relative order of remaining elements. Because every element is visited exactly once, the time complexity is O(n) and the algorithm uses constant extra memory O(1). This pattern frequently appears in array filtering problems and is a classic application of the two pointers technique.
Approach 2: Two-Pointer with Swap from End (Time: O(n), Space: O(1))
This variation avoids unnecessary writes when many elements equal val. Use two pointers: one starting from the beginning and another from the end of the array. When the left pointer encounters val, swap it with the element at the right pointer and decrease the right pointer. If the element at the left pointer is valid, simply move forward.
The insight here is that order does not matter for this problem. Swapping with the end quickly pushes unwanted values out of the active region. Each swap shrinks the valid search space from the right side, which keeps the algorithm linear with O(n) time and constant O(1) space. This version can perform fewer writes when many elements must be removed.
Recommended for interviews: The overwrite two-pointer solution is the most commonly expected answer. It demonstrates clear understanding of in-place array manipulation and pointer movement. The swap-based method is a useful optimization when order is irrelevant and shows deeper knowledge of two-pointer tradeoffs. Mentioning both approaches during interviews signals strong problem-solving depth.
Approach 1: Two-pointer Approach
In this approach, we use two pointers starting at the beginning of the array. One pointer, called 'i', iterates over each element of the array, while the second pointer, called 'j', records the position of where to insert a new element that is not equal to 'val'. Whenever we encounter an element not equal to 'val', we place it at the position pointed by 'j' and increment 'j'. The final value of 'j' will give us the length of the modified array where elements are not equal to 'val'.
def removeElement(nums, val):
j = 0
for i in range(len(nums)):
if nums[i] != val:
nums[j] = nums[i]
j += 1
return jpublic class Solution {
public int removeElement(int[] nums, int val) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[j++] = nums[i];
}
}
return j;
}
}#include <vector>
int removeElement(std::vector<int>& nums, int val) {
int j = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != val) {
nums[j++] = nums[i];
}
}
return j;
}function removeElement(nums, val) {
let j = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== val) {
nums[j++] = nums[i];
}
}
return j;
}#include <stdio.h>
int removeElement(int* nums, int numsSize, int val) {
int j = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] != val) {
nums[j++] = nums[i];
}
}
return j;
}public class Solution {
public int RemoveElement(int[] nums, int val) {
int j = 0;
for (int i = 0; i < nums.Length; i++) {
if (nums[i] != val) {
nums[j++] = nums[i];
}
}
return j;
}
}This Python implementation uses a similar concept with the 'j' pointer ensuring non-'val' numbers are consolidated at the start. 'i' traverses each element.
Time Complexity: O(n), a single traversal of nums.
Space Complexity: O(1), adjustments are in-place.
Approach 2: Two-pointer with Swap Approach
This method uses a two-pointer technique but in a different manner. Here, one pointer (i) starts from the beginning and the other pointer (end) starts from the end of the array. As long as i <= end, we check each element. If nums[i] equals val, we swap it with the element at nums[end] and decrement end. If not, increment i. This ensures that values to be removed accumulate at the end of the array, and relevant values are compacted at the front.
def removeElement(nums, val):
end = len(nums) - 1
i = 0
while i <= end:
if nums[i] == val:
nums[i] = nums[end]
end -= 1
else:
i += 1
return end + 1public class Solution {
public int removeElement(int[] nums, int val) {
int end = nums.length - 1;
int i = 0;
while (i <= end) {
if (nums[i] == val) {
nums[i] = nums[end--];
} else {
i++;
}
}
return end + 1;
}
}#include <vector>
int removeElement(std::vector<int>& nums, int val) {
int end = nums.size() - 1;
int i = 0;
while (i <= end) {
if (nums[i] == val) {
nums[i] = nums[end--];
} else {
i++;
}
}
return end + 1;
}function removeElement(nums, val) {
let end = nums.length - 1;
let i = 0;
while (i <= end) {
if (nums[i] === val) {
nums[i] = nums[end--];
} else {
i++;
}
}
return end + 1;
}#include <stdio.h>
int removeElement(int* nums, int numsSize, int val) {
int end = numsSize - 1;
int i = 0;
while (i <= end) {
if (nums[i] == val) {
nums[i] = nums[end--];
} else {
i++;
}
}
return end + 1;
}public class Solution {
public int RemoveElement(int[] nums, int val) {
int end = nums.Length - 1;
int i = 0;
while (i <= end) {
if (nums[i] == val) {
nums[i] = nums[end--];
} else {
i++;
}
}
return end + 1;
}
}Using swapping, this Python function streamlines removal of 'val'. Being linear time, it lines up non-targets by reusing available space.
Time Complexity: O(n), single traversal suffices.
Space Complexity: O(1), augments solution's efficacy.
Approach 3: One Pass
We use the variable k to record the number of elements that are not equal to val.
Traverse the array nums, if the current element x is not equal to val, then assign x to nums[k], and increment k by 1.
Finally, return k.
The time complexity is O(n) and the space complexity is O(1), where n is the length of the array nums.
function removeElement(nums: number[], val: number): number {
let k: number = 0;
for (const x of nums) {
if (x !== val) {
nums[k++] = x;
}
}
return k;
}func removeElement(nums []int, val int) int {
k := 0
for _, x := range nums {
if x != val {
nums[k] = x
k++
}
}
return k
}impl Solution {
pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 {
let mut k = 0;
for i in 0..nums.len() {
if nums[i] != val {
nums[k] = nums[i];
k += 1;
}
}
k as i32
}
}class Solution {
/**
* @param Integer[] $nums
* @param Integer $val
* @return Integer
*/
function removeElement(&$nums, $val) {
for ($i = count($nums) - 1; $i >= 0; $i--) {
if ($nums[$i] == $val) {
array_splice($nums, $i, 1);
}
}
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Two-pointer Approach | Time Complexity: O(n), a single traversal of nums. |
| Two-pointer with Swap Approach | Time Complexity: O(n), single traversal suffices. |
| One Pass | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Two-Pointer (Overwrite) | O(n) | O(1) | General case when you want a simple linear scan and to preserve relative order of elements |
| Two-Pointer with Swap from End | O(n) | O(1) | When element order does not matter and many values must be removed, reducing unnecessary writes |
Frequently asked questions
Is Remove Element easy or hard?
Remove Element is classified as an Easy problem on LeetCode. The challenge focuses on understanding in-place array updates and pointer movement rather than complex data structures or algorithms.
Remove Element Python/Java solution
Python and Java implementations both follow the same two-pointer logic. Iterate through the array, copy valid elements forward, and return the final write index as the new length. The approach runs in O(n) time and O(1) space in both languages.
How to solve Remove Element in O(n)?
Iterate through the array with a read pointer and maintain a write pointer for the next valid position. When the current value is not equal to the target value, copy it to the write index and increment the write pointer. After one pass, the write pointer represents the new array length.
What is the best approach for Remove Element?
The standard solution uses a two-pointer overwrite technique. One pointer scans the array while another tracks the position to place the next valid element. This removes unwanted values in-place with O(n) time and O(1) extra space, which is the optimal complexity for this problem.
Is Remove Element asked at Google/Amazon/Meta?
Remove Element is a classic entry-level array manipulation problem commonly used in technical interviews and coding screens. Variations of this in-place filtering pattern have appeared in interviews at companies like Amazon, Meta, and other large tech firms.
What data structure is used in Remove Element?
The problem primarily uses arrays combined with the two-pointer technique. No additional data structures are required because the algorithm modifies the input array directly while tracking positions using indices.
What is the time complexity of Remove Element?
The optimal algorithms run in O(n) time because every element in the array is inspected once. Space complexity remains O(1) since the modification happens directly inside the input array without allocating additional data structures.
