Find All Numbers Disappeared in An Array

Given n numbers between 1 and n, find which numbers in that range never appear.

You are given an array nums of n integers, and each of them is between 1 and n. Some numbers may appear more than once, so others may not appear at all. Return every number from 1 to n that does not appear in the array. Try to do it in O(n) time, with no extra memory besides the list you return.

Example 1
Input: nums = [4, 3, 2, 7, 8, 2, 3, 1]
Output: [5, 6]
Example 2
Input: nums = [1, 1]
Output: [2]
Solution

The Idea

Picture a box that should hold eight tickets, numbered 1 to 8. Someone took a few tickets out and put in copies of others. Example 1 is that box: 4, 3, 2, 7, 8, 2, 3, 1. The 2 and the 3 are there twice, so two other numbers must be gone, and they are 5 and 6.

How would you find them by hand? You would write 1 to 8 on a sheet, go through the tickets, and tick off each number you see. The numbers left without a tick are the missing ones. In code, that sheet is a set, a collection that remembers which values were added to it. It takes as much extra memory as the array. Can we keep the ticks somewhere we already have?

The array itself has exactly n positions, numbered 0 to n - 1. These positions are called indexes, and we will also call them slots. Every value is between 1 and n, so every value v has a slot of its own: index v - 1. Value 1 belongs to slot 0, value 4 to slot 3, value 8 to slot 7.

To tick off a value, we can mark its slot by making the number there negative. A minus sign does not change the size of the number, so the slot still remembers what it held. Look at the picture below.

The array 4, 3, 2, 7, 8, 2, 3, 1 before and after marking. Value 4 marks slot 3 by making it negative. After every value has marked its slot, only slots 4 and 5 are still positive, so 5 and 6 are missing.

The top row is the array before we start. The first value, 4, marks slot 3, so the 7 there becomes -7. The 3 marks slot 2, the 2 marks slot 1, and so on through the array. The bottom row shows the array after every value has marked its slot.

Now read the bottom row. Six slots are negative, because some value marked them. Slots 4 and 5 still hold 8 and 2, both positive. No value marked them, so the values that belong there, 5 and 6, never appeared. The array has served as its own tick sheet.

Solution Approach

Turning that idea into code means settling three things: where to keep the marks, how to mark a slot without losing its value, and how to read the answer.

Where to keep the marks

What is the simplest way? For each number from 1 to n, search the whole array for it. That is n searches of n steps each, about 1 million steps for 1,000 numbers. A HashSet, a Java set that finds a value in about one step, brings this down to O(n) time. First add every value to the set, then check 1 to n against it. It is fast, but the set holds up to n values of extra memory.

Marking slots in the array needs no extra memory, because each value already has its slot at index v - 1.

Marking a slot without losing its value

What happens when the value we read was itself made negative earlier? In the picture, value 4 made the 7 in slot 3 negative. Later the loop reaches slot 3 and reads -7, not 7. Math.abs, which drops the minus sign, gives back 7, and 7 still points at slot 6.

What about a value that appears twice? Example 1 has two 2s, and both point at slot 1. Simply flipping the sign would undo the first mark on the second visit. So a slot is made negative only when it is still positive. A marked slot stays marked.

Reading the answer

After the marking pass, a second pass walks the slots. A slot i that is still positive was never marked, so the number i + 1 never appeared, and it goes into the result.

The method changes the array it is given. If the caller still needs the array, an optional last pass can restore it by making every number positive again.

Java Solution

The method findDisappearedNumbers works in these steps:

  1. First, go through the array with a loop that reads each value x. Its slot is idx = Math.abs(x) - 1, with Math.abs because an earlier value may have made x negative already.
  2. If nums[idx] is still positive, make it negative. That marks the value idx + 1 as seen. A slot that is already negative is left alone.
  3. Create an empty list, missing. Then a second loop moves i over every slot, and each slot that is still positive adds i + 1 to missing.
  4. Return missing.

The main method runs both examples, an array with every number present, an array where one value fills every position, and an array of just one number.

Java
import java.util.ArrayList;
import java.util.List;

public class FindMissingNumbersFromArray {

    public static List<Integer> findDisappearedNumbers(int[] nums) {
        for (int x : nums) {
            int idx = Math.abs(x) - 1;        // abs: this value's own slot may be marked already
            if (nums[idx] > 0) {
                nums[idx] = -nums[idx];       // mark: value idx + 1 was seen
            }
        }
        List<Integer> missing = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                missing.add(i + 1);           // nobody marked slot i, so i + 1 never appeared
            }
        }
        return missing;
    }

    public static void main(String[] args) {
        System.out.println(findDisappearedNumbers(new int[] {4, 3, 2, 7, 8, 2, 3, 1}));
        System.out.println(findDisappearedNumbers(new int[] {1, 1}));
        System.out.println(findDisappearedNumbers(new int[] {3, 1, 2}));
        System.out.println(findDisappearedNumbers(new int[] {2, 2, 2, 2}));
        System.out.println(findDisappearedNumbers(new int[] {1}));
    }
}

Running it prints:

Output
[5, 6]
[2]
[]
[1, 3, 4]
[]

The first two lines, [5, 6] and [2], answer the two examples. Look at the second one: the two 1s both point at slot 0, and only 2 is reported. Without the check that a slot is still positive, the second 1 would flip slot 0 back, and that line would print [1, 2].

The third line is empty because [3, 1, 2] holds every number from 1 to 3. In the fourth line, [2, 2, 2, 2] marks only slot 1, so 1, 3 and 4 are missing. The last line is the smallest array: one number, which must be 1, so nothing is missing.

Math.abs matters too. Drop it, and [2, 1] fails: the 2 turns the 1 into -1, the loop then reads -1 as a value, and index -2 throws an ArrayIndexOutOfBoundsException.

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

Complexity

The work is two passes over the array, and the marks live in the array itself.

  • Time: O(n), where n is the length of the array. The first loop marks one slot per value, and the second reads each slot once, so each pass takes n constant-time steps.
  • Space: O(1) besides the output. The marks are the minus signs in the input array, so the only extra storage is idx and the loop index. The missing list is the answer itself.

Using each value as an index into the same array also solves First Missing Positive.