Skip to main content

5. Remove Element

easyAsked at Spotify

Remove all occurrences of a target value in place and return the new length.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an array nums and a value val, remove all instances of that value in place. Return the new length k; the first k slots of nums must contain the surviving elements.

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50

Examples

Example 1

Input
nums=[3,2,2,3], val=3
Output
2 with nums=[2,2,_,_]

Example 2

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

Approaches

1. Brute force

Filter into a new array then copy back

Time
O(n)
Space
O(n)
const filtered = nums.filter(x => x !== val);
for (let i=0;i<filtered.length;i++) nums[i]=filtered[i];
return filtered.length;

Tradeoff:

2. Two pointers

Write pointer advances only when current value should be kept. Single pass, in place.

Time
O(n)
Space
O(1)
function removeElement(nums, val) {
  let write = 0;
  for (let read = 0; read < nums.length; read++) {
    if (nums[read] !== val) {
      nums[write++] = nums[read];
    }
  }
  return write;
}

Tradeoff:

Spotify-specific tips

Spotify uses this to verify you can stream-filter without allocating — relevant to how their audio-event pipelines strip blacklisted ad IDs from listening logs.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Remove Element and other Spotify interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →