5. Remove Element
easyAsked at N26Remove all instances of a given value from an array in-place. N26 reframes this as filtering reversed transactions out of a daily settlement batch.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer array nums and an integer val, remove all occurrences of val from nums in-place. Return the number of elements that are not equal to val; the first k elements should hold the kept values.
Constraints
0 <= nums.length <= 1000 <= nums[i], val <= 50Order of remaining elements may change
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. Splice loop
Remove each occurrence with array splice.
- Time
- O(n^2)
- Space
- O(1)
for (let i=nums.length-1;i>=0;i--)
if (nums[i]===val) nums.splice(i,1);
return nums.length;Tradeoff:
2. Two-pointer write index
Write pointer advances only on keepers.
- 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];
k++;
}
}
return k;
}Tradeoff:
N26-specific tips
N26 reviewers value confirming whether order matters before optimizing; for ledger lines order is usually load-bearing, so call that assumption out.
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 N26 interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →