Skip to content

Remove Element

Given an integer array nums and an integer val, remove all occurrences of val 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, then you need to do the following things to be accepted:

  • Change the first k elements of nums such that they contain all the elements which are not equal to val.
  • The remaining elements of nums are not important as well as the size of nums.
  • Return k.
InputvalOutputArray AfterExplanation
[3,2,2,3]32[2,2,_,_]The first 2 elements are [2, 2]; rest don’t matter
[0,1,2,2,3,0,4,2]25[0,1,4,0,3,_,_,_]The first 5 elements contain no 2
[2]31[2]No element equals 3
  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100
ApproachTimeSpaceBest When
Two PointersO(n)O(1)General case — single pass, optimal space
Brute ForceO(n²)O(1)Array is tiny, demonstrating the concept
  • Pick Two Pointers to understand the efficient partition technique — it’s the expected solution in interviews.
  • Pick Brute Force if you’re still learning how to modify arrays in-place.
Optimal Solution
Two Pointers
O(n) time · O(1) space
Simple Approach
Brute Force
O(n²) time · O(1) space
★ Recommended

Use two pointers: read scans the array, and write tracks where to place non-val elements. When read finds a value that is not val, copy it to the write position and increment both pointers. The first write elements will contain all non-val values.

The key insight is that we partition the array into two regions: the first write elements are valid, and the rest are ignored.

⏱ Time O(n) Single pass 💾 Space O(1) No extra data structures

Input: nums = [0,1,2,2,3,0,4,2], val = 2

Stepreadwritenums[read]ActionArray State
00000 ≠ 2 → copy to write[0,1,2,2,3,0,4,2], write++
11111 ≠ 2 → copy to write[0,1,2,2,3,0,4,2], write++
22222 == 2 → skip[0,1,2,2,3,0,4,2], read++ only
33222 == 2 → skip[0,1,2,2,3,0,4,2], read++ only
44233 ≠ 2 → copy to write[0,1,3,2,3,0,4,2], write++
55300 ≠ 2 → copy to write[0,1,3,0,3,0,4,2], write++
66444 ≠ 2 → copy to write[0,1,3,0,4,0,4,2], write++
77522 == 2 → skipDone, return 5

Final result: First 5 elements [0, 1, 3, 0, 4] contain no 2.

Animated walkthrough

How two pointers partition the array

Use Next or Autoplay to watch the read pointer scan for non-val elements while the write pointer builds the valid partition.

Step 1 of 9
Waiting to begin...
Array state
Memory / lookup state

function removeElement(nums, val):
write = 0
for read in range(len(nums)):
if nums[read] != val:
nums[write] = nums[read]
write++
return write
remove_element_two_pointer.py
"""
Remove all occurrences of a value in-place from an array and return the new length.
Approach: Two Pointers
Use a 'write' pointer to place non-val elements and a 'read' pointer to scan the array.
When read finds a non-val element, copy it to the write position and advance both.
When read finds a val element, skip it and only advance read.
Time Complexity: O(n) — single pass through the array
Space Complexity: O(1) — no extra data structures
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2
Array after: [2,2,_,_]
Explanation: The first 2 elements are [2, 2]; elements after position 2 are ignored.
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5
Array after: [0,1,4,0,3,_,_,_]
Explanation: The first 5 elements contain no 2.
"""
from typing import List
def remove_element(nums: List[int], val: int) -> int:
write = 0
for read in range(len(nums)):
if nums[read] != val:
nums[write] = nums[read]
write += 1
return write
# Test cases
print(remove_element([3, 2, 2, 3], val=3)) # 2
print(remove_element([0, 1, 2, 2, 3, 0, 4, 2], val=2)) # 5
print(remove_element([2], val=3)) # 1
print(remove_element([], val=0)) # 0
✓ Simple

Scan the array from the beginning. When you find an element equal to val, remove it by shifting all subsequent elements left by one position. Repeat until no more elements equal val are found.

This approach is simple to understand but is inefficient because each removal triggers a shift operation that takes O(n) time.

⏱ Time O(n²) Shift per removal 💾 Space O(1) No extra data structures

Input: nums = [3,2,2,3], val = 3

Stepinums[i]ActionArray StateExplanation
0033 == 3 → remove[2,2,3]Shift elements left, length 3
1022 ≠ 3 → skip[2,2,3]Move to next element
2122 ≠ 3 → skip[2,2,3]Move to next element
3233 == 3 → remove[2,2]Shift elements left, length 2
Done[2,2]Return 2

Final result: First 2 elements are [2, 2].

function removeElementBruteForce(nums, val):
i = 0
while i < len(nums):
if nums[i] == val:
remove nums[i] // Shift all elements after i one position left
else:
i++
return len(nums)
remove_element_brute_force.py
"""
Remove all occurrences of a value in-place from an array and return the new length.
Approach: Brute Force
Scan the array. When an element equals val, remove it by shifting all subsequent elements
left by one position. Repeat until no more elements equal val are found.
Do not increment the index after removal so the shifted elements are re-examined.
Time Complexity: O(n²) — worst case when all elements equal val, each removal is O(n)
Space Complexity: O(1) — no extra data structures
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2
Array after: [2,2,_,_]
Explanation: First 3 is removed, then second 3 is removed.
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5
Array after: [0,1,4,0,3,_,_,_]
Explanation: Each 2 is removed by shifting subsequent elements left.
"""
from typing import List
def remove_element(nums: List[int], val: int) -> int:
i = 0
while i < len(nums):
if nums[i] == val:
nums.pop(i) # Remove element and shift all elements after i one position left
else:
i += 1
return len(nums)
# Test cases
print(remove_element([3, 2, 2, 3], val=3)) # 2
print(remove_element([0, 1, 2, 2, 3, 0, 4, 2], val=2)) # 5
print(remove_element([2], val=3)) # 1
print(remove_element([], val=0)) # 0
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
remove_element_optimized.py
"""
Solution for Remove Element
"""
def solve():
"""Implementation for approach 3 of Remove Element"""
pass
if __name__ == "__main__":
print("Solution ready")