5. Remove Element
easyAsked at EtsyStrip 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 <= 1000 <= nums[i], val <= 50
Examples
Example 1
nums = [3,2,2,3], val = 32, nums = [2,2,_,_]Example 2
nums = [0,1,2,2,3,0,4,2], val = 25Approaches
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.
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 →