5. Remove Element
easyAsked at KlarnaRemove all occurrences of a value in an array in place and return the new length.
By Sam K., 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 count of remaining elements. The order of the remaining elements may be changed.
Constraints
0 <= nums.length <= 1000 <= nums[i] <= 500 <= val <= 100
Examples
Example 1
Input
nums = [3,2,2,3], val = 3Output
2, nums = [2,2,_,_]Example 2
Input
nums = [0,1,2,2,3,0,4,2], val = 2Output
5, nums = [0,1,4,0,3,_,_,_]Approaches
1. Filter copy
Filter to new array then 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 pointers
Slow pointer is write index; skip over matches as fast scans.
- Time
- O(n)
- Space
- O(1)
function removeElement(nums, val) {
let slow = 0;
for (let fast = 0; fast < nums.length; fast++) {
if (nums[fast] !== val) {
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}Tradeoff:
Klarna-specific tips
Klarna favors compaction loops since their risk engine prunes rejected installment offers from candidate arrays in tight inner loops.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.