Sitemap
Alan Martins

Alan Martins

Senior Software Developer at Nubank

Remove Element

3 min readJun 19, 2025

--

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 val are placed in the first k positions of the array.
  • Return k, which represents the count of elements that are not equal to val.
  • The elements beyond index k do not matter — they can be anything.

You are not required to resize the array — only to ensure the first k elements are valid.

How the Algorithm Works

  • We use a pointer k to 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 to nums[k] and increment k.
  • 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.
Press enter or click to view image in full size

Step 2: First Comparison

  • Check nums[0] → 1 ≠ 2 → it's a valid value.
  • Place 1 at nums[0] (same position).
  • Increment k → 1.
Press enter or click to view image in full size

Step 3: Find a Value Equal to val

  • Check nums[1] → 2 = 2 → equals val.
  • Skip — no change to k.
Press enter or click to view image in full size

Step 4: Find Another Valid Value

  • Check nums[3] → 3 ≠ 2 → it's a valid value.
  • Place 3 at nums[1].
  • Increment k → 2.
Press enter or click to view image in full size

Step 5: Completion

  • The process is complete.
  • The first k elements ([1, 3]) are the values not equal to val.
  • Return k = 2.
  • The values beyond index k are irrelevant.
Press enter or click to view image in full size

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 k

--

Alan Martins
Alan Martins

Written by Alan Martins

Senior Software Developer at Nubank