5. Remove Element
easyAsked at SoFiIn-place removal of a target value — at SoFi this becomes filtering reversed transactions from a payment batch.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array and a value, remove all instances of that value in-place and return the new length.
Constraints
0 <= nums.length <= 1000 <= nums[i] <= 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. Brute force
Filter into a new array and copy back.
- Time
- O(n)
- Space
- O(n)
const filtered = nums.filter(x => x !== val);
for (let i = 0; i < filtered.length; i++) nums[i] = filtered[i];
return filtered.length;Tradeoff:
2. Two pointers
Write index advances only when current value is not val. O(1) extra space — SoFi's expected solve.
- Time
- O(n)
- Space
- O(1)
function removeElement(nums, val) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== val) nums[write++] = nums[read];
}
return write;
}Tradeoff:
SoFi-specific tips
SoFi engineers expect the two-pointer trick and a comment linking it to in-place filtering of voided ACH transfers without reallocating buffers.
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 SoFi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →