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
Example 1
Output: [5, 6]
Example 2
Output: [2]
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 vv - 1
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 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
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
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 ii + 1
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
- First, go through the array with a loop that reads each value
. Its slot isx , withidx = Math.abs(x) - 1 because an earlier value may have madeMath.abs negative already.x - If
is still positive, make it negative. That marks the valuenums[idx] as seen. A slot that is already negative is left alone.idx + 1 - Create an empty list,
. Then a second loop movesmissing over every slot, and each slot that is still positive addsi toi + 1 .missing - Return
.missing
The main
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:
[5, 6]
[2]
[]
[1, 3, 4]
[]
The first two lines, [5, 6][2][1, 2]
The third line is empty because [3, 1, 2][2, 2, 2, 2]
Math.abs[2, 1]ArrayIndexOutOfBoundsException
The original implementation,
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
and the loop index. Theidx list is the answer itself.missing
Using each value as an index into the same array also solves