5. Remove Element
easyAsked at UnityRemove all occurrences of a value from an array in place. Unity uses this to test entity-list compaction patterns.
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 not equal to val; the relative order is not required.
Constraints
0 <= nums.length <= 1000 <= nums[i], val <= 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. Filter copy
Allocate new array of non-val values 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-pointer compaction
Write pointer keeps non-val values, read pointer scans the array.
- Time
- O(n)
- Space
- O(1)
function removeElement(nums, val) {
let w = 0;
for (let r=0;r<nums.length;r++) {
if (nums[r] !== val) nums[w++] = nums[r];
}
return w;
}Tradeoff:
Unity-specific tips
Unity frames this as despawn-and-compact for active entity lists where allocating a parallel array breaks the frame budget.
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 Unity interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →