Skip to main content

5. Remove Element

easyAsked at SoFi

In-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 <= 100
  • 0 <= nums[i] <= 50

Examples

Example 1

Input
nums = [3,2,2,3], val = 3
Output
2, nums = [2,2,_,_]

Example 2

Input
nums = [0,1,2,2,3,0,4,2], val = 2
Output
5

Approaches

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.

Output

Press Run or Cmd+Enter to execute

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 →