Remove Element
LeetCode 27 · Easy · solution, intuition & step-by-step walkthrough
Keep-if-not-val with a write index.
This is how I solved Remove Element (LeetCode 27), an easy problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Scan once and copy every element that isn't val to the next write position. Whatever is left past the write index doesn't matter.
Approach
- 1
insert_index = 0.
- 2
For each num ≠ val, write it at insert_index and advance.
- 3
Return insert_index.
How I solved it
Write pointerPythonO(n) time · O(1) space
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
insert_index=0
for num in nums:
if num!=val:
nums[insert_index]=num
insert_index+=1
return insert_indexRemove Element — FAQ
What is the intuition behind Remove Element?
Scan once and copy every element that isn't val to the next write position. Whatever is left past the write index doesn't matter.
How do you solve Remove Element (LeetCode 27)?
1. insert_index = 0. 2. For each num ≠ val, write it at insert_index and advance. 3. Return insert_index.
What is the time and space complexity of Remove Element?
Time: O(n). Space: O(1). (Accepted approach: Write pointer.)
What are common mistakes in Remove Element?
Order beyond the first k elements is irrelevant.