Skip to main content

5. Remove Element

easyAsked at Etsy

Strip a target value from an array in place — Etsy's quick pointer-discipline check.

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

Problem

Given an array nums and a value val, remove all occurrences of val in-place. Return the count k of remaining elements; the first k positions of nums must hold them in any order.

Constraints

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

Examples

Example 1

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

Example 2

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

Approaches

1. Filter copy

Build a fresh array of non-val items.

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

Tradeoff:

2. Two pointers

Read with r, write only when nums[r] !== val.

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

Tradeoff:

Etsy-specific tips

Etsy will ask how you'd extend this to remove out-of-stock listings from a search-results array on the fly — frame it as the same write-pointer trick.

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 Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →