Remove Element
This is another one of those “easy” problems that has a few tricky details. The goal is to remove all occurrences of a given value from an array in-place, without allocating extra space — meaning the array must be updated directly.
Understanding the Problem
Given an array nums and a value val, the goal is to remove all occurrences of val in-place, without creating a new array. However, this does not mean physically shrinking the array.
Get Alan Martins’s stories in your inbox
Join Medium for free to get updates from this writer.
What the problem expects is:
- Rearrange the elements in-place so that all values different from
valare placed in the firstkpositions of the array. - Return
k, which represents the count of elements that are not equal toval. - The elements beyond index
kdo not matter — they can be anything.
You are not required to resize the array — only to ensure the first
kelements are valid.
How the Algorithm Works
- We use a pointer
kto track the position where the next valid (non-val) element should be placed. - Start with
k = 0, meaning the beginning of the array. - Loop through each element:
- If the current element is not equal to
val, assign it tonums[k]and incrementk. - If it equals
val, skip it.
Step-by-Step Example
Step 1: Initialization
- Set
val = 2→ the value to remove. - Set
k = 0→ the index where the next valid value will be placed.
Step 2: First Comparison
- Check
nums[0]→1 ≠ 2→ it's a valid value. - Place
1atnums[0](same position). - Increment
k → 1.
Step 3: Find a Value Equal to val
- Check
nums[1]→2 = 2→ equalsval. - Skip — no change to
k.
Step 4: Find Another Valid Value
- Check
nums[3]→3 ≠ 2→ it's a valid value. - Place
3atnums[1]. - Increment
k → 2.
Step 5: Completion
- The process is complete.
- The first
kelements ([1, 3]) are the values not equal toval. - Return
k = 2. - The values beyond index
kare irrelevant.
Solution
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 kLeetcode Problem: https://leetcode.com/problems/remove-element/description/








