5. Remove Element
easyAsked at MercuryRemove all occurrences of a value from an array in-place.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place and return the new length. The order of the elements may be changed.
Constraints
0 <= nums.length <= 1000 <= nums[i], val <= 50
Examples
Example 1
nums = [3,2,2,3], val = 3k=2, nums=[2,2,_,_]Example 2
nums = [0,1,2,2,3,0,4,2], val = 2k=5Approaches
1. Filter and rewrite
Build a new array without val, copy back.
- 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-pointer overwrite
Write pointer advances only when current value is kept; read pointer always advances. In-place and linear.
- Time
- O(n)
- Space
- O(1)
function removeElement(nums, val) {
let k = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== val) {
nums[k++] = nums[i];
}
}
return k;
}Tradeoff:
Mercury-specific tips
At Mercury, this maps to filtering out cancelled wire instructions before sending the day's NACHA batch upstream, so emphasize that the originating-account index must remain stable post-filter.
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 Mercury interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →