Remove Element
Remove every copy of a value from an array in place and return how many values are left.
You are given an array of integers numsvalvalnumskknums
Example 1
Output: 2, nums = [2, 2, _, _]
Example 2
Output: 5, nums = [0, 1, 3, 0, 4, _, _, _]
The Idea
Picture eight boxes in a row on a shelf, holding 0, 1, 2, 2, 3, 0, 4 and 2, and you are asked to take out every 2. On a real shelf you lift the 2s out and push the other boxes together. A Java array cannot do that: its length is fixed when it is created, so no position can disappear.
So what does removing mean here? Example 2 answers it. The array still has eight positions afterwards, but the first five now hold 0, 1, 3, 0 and 4, the values that are not 2, and the method returns 5. Nobody reads the last three positions.
How do the kept values get to the front? The plain way does what the shelf does: each time a 2 turns up, shift every value after it one place left. That works, but a 2 near the start makes almost the whole array move, and every further 2 makes it move again.
Notice where each kept value has to end up. It only ever moves left, and it lands in the first free position at the front. So one walk through the array is enough: read each value, skip it if it is a 2, and otherwise copy it into the next free position. Look at the picture below.
The top row is the array before. The walk reads index 0 and index 1 and copies 0 and 1 into the first two positions, where they already are. Index 2 and index 3 hold 2s, so they are skipped. Index 4 holds 3, which goes into position 2, the next free one. Then 0 goes to position 3 and 4 to position 4, and the 2 at index 7 is skipped too.
The bottom row is the array after. Five values were copied, so the answer is 5, and the picture marks them as the first k = 5 positions. The last three positions, marked "left over, ignored", still hold 0, 4 and 2 from before.
So the walk needs two positions in the same array: one that reads every value, and one that marks where the next kept value is written. Moving two positions through an array like this is called the two-pointer technique, and
Solution Approach
Turning that idea into code means settling three things: how the read and write positions move, why a write never destroys a value that is still needed, and how to write less when only a few values must go.
Moving the read and write positions
How do the two positions move? The read position moves one step for every value, so a plain loop over the array is enough. The write position, k
That gives k
Compare that with shifting. Shifting can move almost n values for every copy of val
Overwriting safely
Can a write wipe out a value that has not been read yet? No. kkk
Fewer writes when val is rare
Is there a way to write less? The walk copies every kept value, even 0 and 1, which only land on themselves. When valendinums[i]valnums[end - 1]end
After such a copy, ival
Java Solution
The method removeElement
- First, set
to 0. It marks the next free position at the front ofk , and it counts the kept values.nums - Read the array from start to end with a for-each loop, which hands each value to
in turn. The loop plays the part of the read position.x - Inside the loop, if
is notx , write it intoval and movenums[k] one step withk . Ifk++ equalsx , do nothing, so it is skipped.val - When the loop ends, return
.k
The mainvalvalk
import java.util.Arrays;
public class RemoveElement {
public static int removeElement(int[] nums, int val) {
int k = 0; // nums[0..k-1] holds the kept values
for (int x : nums) {
if (x != val) {
nums[k++] = x; // copy a kept value to the next free position
}
}
return k;
}
static void run(int[] nums, int val) {
String before = Arrays.toString(nums);
int k = removeElement(nums, val);
System.out.println("remove " + val + " from " + before + ": k = " + k
+ ", kept " + Arrays.toString(Arrays.copyOf(nums, k)));
System.out.println(" array after: " + Arrays.toString(nums));
}
public static void main(String[] args) {
run(new int[] {3, 2, 2, 3}, 3);
run(new int[] {0, 1, 2, 2, 3, 0, 4, 2}, 2);
run(new int[] {4, 4}, 4);
run(new int[] {1, 2, 3}, 7);
run(new int[] {}, 1);
}
}
Running it prints:
remove 3 from [3, 2, 2, 3]: k = 2, kept [2, 2]
array after: [2, 2, 2, 3]
remove 2 from [0, 1, 2, 2, 3, 0, 4, 2]: k = 5, kept [0, 1, 3, 0, 4]
array after: [0, 1, 3, 0, 4, 0, 4, 2]
remove 4 from [4, 4]: k = 0, kept []
array after: [4, 4]
remove 7 from [1, 2, 3]: k = 3, kept [1, 2, 3]
array after: [1, 2, 3]
remove 1 from []: k = 0, kept []
array after: []
Look at the line array after: [2, 2, 2, 3][3, 2, 2, 3][0, 1, 3, 0, 4, 0, 4, 2]
Removing 4 from [4, 4]k = 0[1, 2, 3]k
The original implementation,
Complexity
The method makes one pass over the array and keeps one counter.
- Time: O(n), for an array of n numbers, because the loop reads each value once and writes it at most once, and nothing is shifted.
- Space: O(1). The kept values overwrite the front of
, sonums is the only extra storage.k