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 nums and a number val. Remove every copy of val from nums in place, which means changing the given array itself instead of building a new one. Return k, the number of values that are left. The first k positions of nums must hold those values, in any order. Whatever sits after them does not matter, and the examples mark those positions with an underscore.

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, 3, 0, 4, _, _, _]
Solution

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.

Removing 2 from 0, 1, 2, 2, 3, 0, 4, 2. The three 2s are skipped. The kept values 0, 1, 3, 0 and 4 are copied, in order, into the first five positions, so k is 5. The last three positions still hold 0, 4 and 2 and are ignored.

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 Two Pointers Basics shows more ways to use it.

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, starts at 0 and moves one step only when a value is kept.

That gives k two jobs at once. It is the next free position, and it is also the number of values kept so far, which is exactly what the method must return.

Compare that with shifting. Shifting can move almost n values for every copy of val, where n is the length of the array, so with many copies the work grows like n². The walk reads each value once and writes it at most once.

Overwriting safely

Can a write wipe out a value that has not been read yet? No. k only moves when the read position moves too, so k is never ahead of it. A write at position k lands on the value just read or on one read earlier. In the picture, position 2 gets the 3 only after the 2 that sat there was read and skipped.

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 val is rare, an optional variant writes less. Keep end, the length of the part of the array still in use, starting at the full length, and walk a position i from the start. When nums[i] equals val, copy nums[end - 1], the last value still in use, into it and reduce end by one.

After such a copy, i stays where it is and is checked again, because the value it just took from the end may also be val. It changes the order of the kept values, which the problem allows, and it is still one pass. The code below uses the simpler walk.

Java Solution

The method removeElement works in these steps:

  1. First, set k to 0. It marks the next free position at the front of nums, and it counts the kept values.
  2. Read the array from start to end with a for-each loop, which hands each value to x in turn. The loop plays the part of the read position.
  3. Inside the loop, if x is not val, write it into nums[k] and move k one step with k++. If x equals val, do nothing, so it is skipped.
  4. When the loop ends, return k.

The main method runs both examples, an array where every value is val, an array without val, and an empty array. For each one it prints k and the kept values, then the whole array, so the left-over positions show too.

Java
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:

Output
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]. Removing 3 from [3, 2, 2, 3] wrote only the first two positions, and the last two still hold 2 and 3 from before. That is why the problem says the rest does not matter. For Example 2 the array ends as [0, 1, 3, 0, 4, 0, 4, 2]: the kept values first, in their original order, then the leftovers from the picture.

Removing 4 from [4, 4] returns k = 0 and leaves the array as it was, since no value was kept and nothing was written. Removing 7 from [1, 2, 3] keeps all three, each copied onto itself. The empty array never enters the loop, so k stays 0.

The original implementation, RemoveElements.java, is on GitHub.

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 nums, so k is the only extra storage.

Move Zeroes uses the same read and write positions, but it keeps the removed values, the zeros, by moving them to the end of the array.