This is the Remove Element problem. Use two pointers: one reads every element, the other marks where the next kept element should be written. Every element that is not equal to val is copied forward.
import java.util.Arrays;
public class RemoveElement {
static int removeElement(int[] nums, int val) {
int k = 0;
for (int num : nums) {
if (num != val) {
nums[k++] = num;
}
}
return k;
}
public static void main(String[] args) {
int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};
int k = removeElement(nums, 2);
System.out.println("New length: " + k);
System.out.println(Arrays.toString(Arrays.copyOf(nums, k)));
}
}New length: 5
[0, 1, 3, 0, 4]
If order does not matter and val is rare, you can swap matching elements with the last element and shrink the array instead, which does fewer writes.
Say clearly that only the first k elements matter after the call; that is how the problem is judged.
A concise interview answer is
I keep a write index k and copy every element that is not equal to val to nums[k], incrementing k each time. After one pass the first k elements are the result and k is the new length, giving O(n) time and O(1) extra space.
Last updated: 11 November 2026
Previous question: Check if all characters in a string have the same number of occurrences.
Next question: Sum of even numbers after each query: update the array and return the sum of even values after every query.