Remove Duplicates From Sorted Array II

Shorten a sorted array in place so that each value appears at most twice.

You are given an array of integers nums, sorted from smallest to largest, where equal values sit next to each other. Remove the extra copies so that each value appears at most twice, keeping the values in their order. Do it in place, inside nums itself, without a second array. Return the number of values kept, k. The first k slots of nums must hold them, and whatever is left in the slots after that does not matter.

Example 1
Input: nums = [1, 1, 1, 2, 2, 3]
Output: 5, nums = [1, 1, 2, 2, 3, _]
Example 2
Input: nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
Output: 7, nums = [0, 0, 1, 1, 2, 3, 3, _, _]
Solution

The Idea

Think of a sorted pile of tickets, each with a number, where you may keep at most two tickets of each number. You go through the pile from the top, and you throw away a ticket only when you already hold two with the same number.

Example 1 works the same way. Reading [1, 1, 1, 2, 2, 3] from the left, the first two 1s are kept and the third 1 is dropped. Both 2s are kept, and so is the 3. That leaves five values, 1, 1, 2, 2 and 3, so the answer is 5. In the output the last slot shows _, because nobody looks at it.

The kept values have to end up at the front of the same array. So as we read along, we copy each value we keep to the next free slot at the front. The front part then always holds the values kept so far, in sorted order. How do we decide, for the value we are reading, that it would be a third copy?

Call the value being read x, and the number of values kept so far k. The kept values sit in nums[0] to nums[k - 1], so nums[k] is the next free slot. Look at the picture below.

The array 1, 1, 1, 2, 2, 3 with k = 2. Reading the third 1, x equals nums[k - 2], so it is a third copy and is skipped. Reading the first 2, x is different from nums[k - 2], so 2 is written into nums[k].

In the top row, two 1s are already kept in slots 0 and 1, so k is 2, and x is the third 1, in the blue box. The orange box is nums[k - 2], the kept value two slots back, and it is also 1. The front part is sorted, so the value between them, nums[k - 1], must be 1 as well. Two 1s are already kept, and x is skipped.

In the bottom row, x is the first 2, and nums[k - 2] is still 1. They are different, so fewer than two 2s are kept so far. The 2 is copied into nums[k], slot 2, and k becomes 3.

So one comparison is enough: x is a third copy exactly when it equals the kept value two slots back. There is no need to count copies.

Solution Approach

Turning that idea into code means settling three things: where the kept values are written, how to spot a third copy, and what to do with the first two values.

Where the kept values go

Why not simply delete each extra copy where it stands? Deleting from the middle of an array means shifting every later value one slot to the left. With many extra copies, that shifting happens again and again, and the work grows with the square of the length.

Writing to the front avoids all shifting. The code keeps two positions in the same array: the read position, which moves over every value, and the write position k, which moves only when a value is kept. Two positions moving through one array like this are called two pointers. k never gets ahead of the read position, because at most one value is written per value read. So a write never covers a value that has not been read yet.

Spotting a third copy

Which value should x be compared with? It must be the kept value nums[k - 2], not the value two places back in the input. The front of the array changes as values are written into it, so an input position may already hold a different value by the time it is checked, and then a value that should stay is dropped.

The first two values

What about the start, when fewer than two values are kept? Then nums[k - 2] does not exist, and no value can have two copies kept yet. So while k is below 2, every value is kept. The check k < 2 comes first, so Java never reads nums[k - 2] with a negative index.

As an optional extension, the same loop allows any limit. Replace 2 with a number m in both places in the check, and each value is kept at most m times.

Java Solution

The method removeDuplicates works in these steps:

  1. First, set k to 0. It counts the values kept so far, and it is also the slot where the next kept value goes.
  2. Read the array from left to right with an enhanced for loop, which hands out each value in turn as x.
  3. For each x, check k < 2 || x != nums[k - 2]. When it holds, write x into nums[k] and add one to k. Otherwise x would be a third copy, and the loop moves on.
  4. When the loop is done, return k.

The main method runs both examples, a run of five 2s, an array with no repeats, a single value and an empty array, and prints k, the kept part and the whole array.

Java
import java.util.Arrays;

public class RemoveDuplicatesFromSortedArrayII {

    public static int removeDuplicates(int[] nums) {
        int k = 0;                            // nums[0..k-1] holds the values kept so far
        for (int x : nums) {
            if (k < 2 || x != nums[k - 2]) {  // not a third copy of x
                nums[k] = x;
                k++;
            }
        }
        return k;
    }

    static void run(int[] nums) {
        int k = removeDuplicates(nums);
        System.out.println("k = " + k + ", kept: " + Arrays.toString(Arrays.copyOf(nums, k))
            + ", whole array: " + Arrays.toString(nums));
    }

    public static void main(String[] args) {
        run(new int[] {1, 1, 1, 2, 2, 3});
        run(new int[] {0, 0, 1, 1, 1, 1, 2, 3, 3});
        run(new int[] {2, 2, 2, 2, 2});
        run(new int[] {1, 2, 3});
        run(new int[] {7});
        run(new int[] {});
    }
}

Running it prints:

Output
k = 5, kept: [1, 1, 2, 2, 3], whole array: [1, 1, 2, 2, 3, 3]
k = 7, kept: [0, 0, 1, 1, 2, 3, 3], whole array: [0, 0, 1, 1, 2, 3, 3, 3, 3]
k = 2, kept: [2, 2], whole array: [2, 2, 2, 2, 2]
k = 3, kept: [1, 2, 3], whole array: [1, 2, 3]
k = 1, kept: [7], whole array: [7]
k = 0, kept: [], whole array: []

Look at the first line: k = 5 and the kept part is [1, 1, 2, 2, 3]. The whole array ends in 3, 3, because the last slot still holds the old 3. That leftover is the _ in Example 1. In the second line, the whole array is [0, 0, 1, 1, 2, 3, 3, 3, 3], and its last two 3s are leftovers in the same way.

The run of five 2s gives k = 2, while the whole array is unchanged. Only k says that the last three 2s no longer count. The array [1, 2, 3] keeps all three values, and the single 7 and the empty array come through without an error, because k < 2 stops the check before nums[k - 2] is read.

What if the check used the input position instead, nums[i] != nums[i - 2], with i as the read position? On [1, 1, 1, 2, 2, 3] that version returns 4 and keeps [1, 1, 2, 3]. When it reads the second 2, at position 4, it compares with position 2. That slot held a 1 in the input, but the first 2 was already written over it, so the second 2 looks like a third copy and is lost.

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

Complexity

The work is a single pass over the array, with one comparison per value.

  • Time: O(n), for an array of n numbers, because the loop reads each value once and does one comparison and at most one write for it.
  • Space: O(1). The kept values are written over the front of nums, and the only extra variable is k.

With 1 in place of 2 in the check, the same loop keeps each value once: see Remove Duplicates from Sorted Array.