Skip to main content

5. Remove Element

easyAsked at GitHub

Remove all occurrences of a value from an array in-place — GitHub's lead-in to pruning broken refs from a packed-refs file without reallocating.

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. Return the number of elements remaining; order of remaining elements can be changed.

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

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, nums = [0,1,4,0,3,_,_,_]

Approaches

1. Brute force

Filter into a new array, copy back.

Time
O(n)
Space
O(n)
const out = nums.filter(x => x !== val);
for (let i=0;i<out.length;i++) nums[i]=out[i];
return out.length;

Tradeoff:

2. Two-pointer overwrite

Read scans entire array; write copies only non-matching values. Final write index equals the new length.

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:

GitHub-specific tips

GitHub probes whether you mutate in-place — same constraint that drives git pack-refs to rewrite the file rather than allocate a new structure.

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 GitHub interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →