Find All Numbers Disappeared in an Array (LeetCode 448): Solution and Explanation

Easy
Array
Hash Table

You are given an array of n integers where every value lies between 1 and n. Some values appear twice and others not at all. Return every number in the range 1 to n that never appears, ideally without extra space beyond the output.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The easy solution builds a set of all values and then lists every number from 1 to n that is not in it. That is linear time but needs O(n) memory. A boolean array of size n + 1 works the same way. The follow-up asks you to avoid that extra memory, so the question is where else the "have I seen this value" information can live.

Because every value is between 1 and n, each value v maps to a unique index v - 1 inside the array you already have. If you could leave a mark at index v - 1 whenever you see v, then after one pass the unmarked indices would tell you exactly which values never showed up. The catch is that the mark must not destroy the number stored at that index, since you still need to read it as part of the pass.

All values start positive, so the sign bit is free to use as the mark. In the first pass, for each element take abs(num) to recover its original value even if it has already been negated, then make the element at index abs(num) - 1 negative. If it is already negative, leave it, which is what makes duplicates harmless. In the second pass, any index i still holding a positive number was never pointed to, so i + 1 is missing.

Approach: Two-pass sign marking

  1. Create an empty result list.
  2. First pass: for each num, compute index = abs(num) - 1, using abs because the element may already be negated.
  3. If nums[index] is positive, negate it to record that index + 1 is present. If it is already negative, leave it alone.
  4. Second pass: loop over every index i from 0 to n - 1.
  5. If nums[i] > 0, no value pointed to this slot, so append i + 1 to result.
  6. Return result.

Step-by-step example

nums = [4, 3, 2, 7, 8, 2, 3, 1]
  1. The values 4, 3, 2, 7 and 8 negate indices 3, 2, 1, 6 and 7, giving [4, -3, -2, -7, 8, 2, -3, -1].
  2. The second 2 points to index 1, which is already negative, so nothing changes. The value -3 points (by absolute value) to index 2, also already negative.
  3. The value -1 points to index 0, which holds 4, so it becomes -4. The array is now [-4, -3, -2, -7, 8, 2, -3, -1].
  4. In the second pass, indices 4 and 5 still hold positive values (8 and 2).
  5. The function returns [5, 6], the numbers that never appeared.

Code: Python, Java, C++

1class Solution:
2    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
3        result = []
4
5        # Phase 1: Mark visited numbers by negating value at index (num - 1)
6        for num in nums:
7            index = abs(num) - 1
8            if nums[index] > 0:
9                nums[index] = -nums[index]
10
11        # Phase 2: Collect indices with positive values (missing numbers)
12        for i in range(len(nums)):
13            if nums[i] > 0:
14                result.append(i + 1)
15
16        return result

Time and space complexity

Time

O(n)

There are two passes over the array, each doing constant work per element.

Space

O(1)

The markers are stored in the signs of the input array, so apart from the returned list no extra memory is used. The input is modified.

Other approaches

Hash set or boolean array (time O(n), space O(n))

Record every value in a set or a seen array of size n + 1, then collect the numbers from 1 to n that were not recorded. It is the clearest solution and leaves the input intact, at the cost of O(n) memory.

Cyclic sort (time O(n), space O(1))

Swap each value into index v - 1 until every slot holds its own value or a duplicate. Then any index i with nums[i] != i + 1 means i + 1 is missing. It uses constant extra space without relying on the sign bit.

Common mistakes

  • Using num - 1 as the index without abs. Elements negated earlier in the pass would produce negative indices, which in Python silently read from the end of the array.
  • Negating unconditionally with nums[index] = -nums[index]. A duplicate would flip the sign back to positive, making a present number look missing. Use -abs(nums[index]) or check the sign first.
  • Returning indices instead of values in the second pass. The missing number at index i is i + 1.
  • Forgetting that the input is mutated. If the caller needs the original array, restore it with absolute values afterward.

Frequently asked questions

How do you find missing numbers without extra space?

Use the array itself as a presence table. Since values are 1 to n, value v marks index v - 1 by making it negative, and any index left positive afterward corresponds to a missing number.

Does the output list count as extra space?

No. By convention the returned list is not counted, so the sign-marking solution is considered O(1) extra space.

How is this related to Find All Duplicates in an Array?

It is the same sign-marking idea. There you report a value when its slot is already negative; here you report the slots that never became negative.