15% off all plans & roadmaps Use code

See plans

Find All Numbers Disappeared in an Array

Updated

TL;DR: Return every value from 1 to n that the array does not contain. Cyclic sort moves each value to the index value minus 1 using swaps, so one final scan finds the gaps in O(n) time and O(1) extra space.

Problem

Given an array nums of n integers where each nums[i] lies in the range [1, n], return every integer in the range [1, n] that does not appear in nums.

Example 1

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

Example 2

Input: nums = [1,1]
Output: [2]

Constraints

  • n == nums.length
  • 1 <= n <= 10^5
  • 1 <= nums[i] <= n

Constraints that matter

  • n up to 10^5 rules out the O(n^2) brute force, which can perform about 10^10 comparisons in the worst case.
  • Every value lies in [1, n], so each value v has a home index v - 1 that exists inside the array. This is what makes in-place placement possible.
  • The follow-up asks for O(1) extra space, so a hash set is only a stepping stone and not the final answer.
  • The returned list can hold almost n values, so the output does not count toward extra space.

View on LeetCode

Hints

Hint 1

The input gives you a fixed range.

Hint 2

Ask the question directly for every candidate.

Solution

Intuition

The input gives you a fixed range. Every value from 1 to n has one home slot, at index value minus 1, and there are exactly n slots for n values. That match between values and indices is the signal for cyclic sort, the pattern where you move each value to its home index.

Picture a row of n mailboxes labeled 1 to n and a pile of n letters, each addressed to one box. The mailboxes are the array slots, each letter is a value, and a box holding the wrong letter marks a missing number.

Watch what a missing value does. Its home slot never receives its own value, so that slot keeps some other value. A duplicate causes a different problem: two copies compete for one home, so one copy stays in a foreign slot. Once every value that can reach its home has moved there, the slots still holding a wrong value point at the missing numbers.

The method works because each swap puts a value into its own home slot, and a settled slot never changes again. The loop therefore ends, and the final scan reads the answer straight from the array. Sorting first also exposes the gaps, but it costs O(n log n) time.

The home-slot idea gets linear time and works in place, so the array is rearranged rather than copied. Reach for it when the values form a permutation or near permutation of a small range such as 1 to n or 0 to n. If values can exceed n, the home index falls outside the array, and a hash set is the right tool instead.

Watch the pattern animation

Worked example

Input: nums = [10, 2, 5, 10, 9, 1, 1, 4, 3, 7]  (so n = 10)
Output: [6, 8]
Explanation: The values 1 through 10 are checked one by one. The values 6 and 8 never appear in the array, so they are the only two returned. The values 10 and 1 each appear twice, and 9 appears once, so duplicates must not create false gaps.

Approach 1: Brute force

Ask the question directly for every candidate. For each value v from 1 to n, scan the whole array to see whether v appears. If the scan finds v, move on. If the scan reaches the end without finding it, v is missing and goes into the result.

This is the first solution most people write. It needs no extra memory beyond a few counters.

Steps

  1. Set n to the length of nums and create an empty result list.
  2. For each candidate v from 1 to n, set a found flag to false.
  3. Scan every element x of nums. If x equals v, set found to true and stop the scan.
  4. If found is still false after the scan, append v to the result.
  5. Return the result.

Dry run

Start with v = 1. The scan reads 10, 2, 5, 10, 9, 1 and stops at index 5, so 1 is present. The value 2 is found at index 1 after two reads. The values 3, 4, 5, 7, 9 and 10 are found at indices 8, 7, 2, 9, 4 and 0.

The value 6 reads all 10 elements and finds nothing, so it goes into the result. The value 8 also reads all 10 elements and is missing, so it goes into the result too. The output is [6, 8].

Complexity

TimeO(n^2)
SpaceO(1) extra, not counting the output list

Let n be the length of the array. The outer loop tries n candidate values, and each candidate triggers a scan of at most n elements, so the total is at most n * n comparisons. A missing value forces a full scan, so the worst case is reached. Only the counters and the flag use extra space, so the extra space is O(1) apart from the output.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        n = len(nums)
        result = []
        for v in range(1, n + 1):
            found = False
            for x in nums:
                if x == v:
                    found = True
                    break
            if not found:
                result.append(v)
        return result

Approach 2: Hash set of seen values

What's slow: every membership check scans the array, so n checks cost n full scans. The insight that fixes it: a hash set answers whether a value is present in O(1) average time. Build the set once from nums, then test each value from 1 to n against it.

The set uses O(n) memory, which the follow-up rules out. It still shows the logic plainly and gives you a correct baseline to compare against.

Steps

  1. Set n to the length of nums.
  2. Insert every value of nums into a hash set. Duplicates collapse into one entry.
  3. For each v from 1 to n, check whether v is in the set.
  4. If v is not in the set, append it to the result.
  5. Return the result.

Dry run

Build the set from the ten values. The duplicates 10 and 1 collapse, so the set holds {10, 2, 5, 9, 1, 4, 3, 7}, which is eight entries.

Now check v from 1 to 10. The values 1, 2, 3, 4 and 5 are in the set. The value 6 is not, so it goes into the result. The value 7 is in the set. The value 8 is not, so it goes into the result. The values 9 and 10 are in the set. The output is [6, 8].

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of the array. Building the set reads n values, and each insert takes O(1) on average, so that step costs O(n). The final loop runs n times with an average O(1) membership test, which gives O(n) total. The set holds at most n distinct values, so the extra space is O(n). Worst-case hash collisions could slow the inserts, but the usual analysis assumes average-case hashing.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        n = len(nums)
        seen = set(nums)  # duplicates collapse here
        result = []
        for v in range(1, n + 1):
            if v not in seen:
                result.append(v)
        return result

The Array - Cyclic Sort infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Array - Cyclic Sort

Part of Array/Matrix Manipulation Patterns

Approach 3: Cyclic sort in placeOptimalArray - Cyclic Sort

What's slow: the hash set spends O(n) memory on a record of presence. The insight that fixes it: each value v has a home slot at index v - 1, and there are exactly n slots. The array can hold the presence record itself.

Swap each value into its home slot. A missing value leaves its home slot holding some other value, and one scan finds those slots.

Before swapping, check whether the home slot already holds the same value. If it does, the current value is a duplicate, so leave it and move on. Otherwise a swap would repeat forever.

Steps

  1. Set i to 0 and n to the length of nums.
  2. While i is less than n, compute j = nums[i] - 1, the home slot of the value at i.
  3. If nums[i] differs from nums[j], swap them and leave i unchanged so the new value at i gets checked.
  4. Otherwise the value is home, or a duplicate already sits in its home, so increase i by 1.
  5. After the loop, scan k from 0 to n - 1. Wherever nums[k] is not k + 1, append k + 1 to the result.
  6. Return the result.

Dry run

The table tracks i, the value at i, its home slot j, and the full array after each step. Five swaps happen, and every other row only advances i.

Stepinums[i]Home jnums[j]ActionArray after step
101097swap[7, 2, 5, 10, 9, 1, 1, 4, 3, 10]
20761swap[1, 2, 5, 10, 9, 1, 7, 4, 3, 10]
30101equal, i to 1unchanged
41212equal, i to 2unchanged
52549swap[1, 2, 9, 10, 5, 1, 7, 4, 3, 10]
62983swap[1, 2, 3, 10, 5, 1, 7, 4, 9, 10]
72323equal, i to 3unchanged
8310910equal, i to 4unchanged
94545equal, i to 5unchanged
105101equal, i to 6unchanged
116767equal, i to 7unchanged
1274310swap[1, 2, 3, 4, 5, 1, 7, 10, 9, 10]
13710910equal, i to 8unchanged
148989equal, i to 9unchanged
15910910equal, i to 10, loop endsunchanged

The final array is [1, 2, 3, 4, 5, 1, 7, 10, 9, 10].

Indices 0 to 4 hold 1 to 5, as expected. Index 5 holds 1 instead of 6, so 6 is missing. Index 6 holds 7, which is correct. Index 7 holds 10 instead of 8, so 8 is missing. Indices 8 and 9 hold 9 and 10, and the output is [6, 8].

Complexity

TimeO(n)
SpaceO(1) extra, not counting the output list

Let n be the length of the array. Each loop iteration either swaps or advances i, and i only moves forward, so there are at most n advances. A swap puts a value into its home slot, and a correct slot never moves again, so there are at most n swaps. The loop runs at most 2n times and the final scan does n checks, so the total is O(n). Only i, j, a temporary variable and a counter are used, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        n = len(nums)
        i = 0
        while i < n:
            j = nums[i] - 1  # home index of the value at i
            if nums[i] != nums[j]:
                nums[i], nums[j] = nums[j], nums[i]
            else:
                i += 1
        result = []
        for k in range(n):
            if nums[k] != k + 1:
                result.append(k + 1)
        return result

Common mistakes

  • Using if (nums[i] != i + 1) as the swap test. Two copies of a value make the swap a no-op, so the loop never ends. Compare against nums[j], the value already in the home slot, and advance when they match.
  • Writing if instead of a loop that stays on i. After if (nums[i] != nums[j]) swap; i++, the value pulled into position i is never checked. Keep i fixed after a swap and advance only when the slot is settled.
  • Checking nums[k] != k in the final scan. Values run from 1 to n, so the home value of index k is k + 1. Use nums[k] != k + 1.
  • Running the final scan before the while loop ends. The array is not yet settled, so the scan reports slots that a later swap would fill. The identification pass must come after the loop.
  • Returning an ArrayList from the Java method. The starter signature returns int[], so the list must be copied into an array first, as the code above does.
  • Calling nums.contains(v) on a list inside the hash approach. Each call scans the array, which brings the work back to O(n^2). Build the set once before the loop.

Edge cases

  • nums = [1] with n = 1: the value sits at its home slot, so the result is [].
  • nums = [1, 1]: slot 0 holds 1 and slot 1 holds a duplicate 1, so the result is [2].
  • nums = [2, 2]: the second 2 cannot reach slot 1 because it already holds 2, so index 0 is wrong and the result is [1].
  • nums = [3, 3, 3]: every value is a duplicate of 3, so the result is [1, 2] and no swap ever occurs.
  • nums already equal to [1, 2, ..., n]: no swaps happen and the result is [].
  • n = 100000 with every value equal to 1: the result holds the 99999 values 2 through 100000, which shows why the output list is excluded from the space bound.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find All Numbers Disappeared in an Array, with how to answer them.

Unlock the follow-ups

Find All Numbers Disappeared in an Array FAQ

What is the time complexity of Find All Numbers Disappeared in an Array?

The cyclic sort solution runs in O(n) time. The swap loop does at most about 2n iterations, and the final scan does n checks. The brute force version scans the array once per candidate value, which gives O(n^2).

Why use cyclic sort for Find All Numbers Disappeared in an Array?

The values lie in the range 1 to n, so each value has a home index inside the array. Moving values to their homes leaves missing numbers visible as wrong slots. The array itself stores the presence record, so the extra space is O(1).

Can Find All Numbers Disappeared in an Array be solved in O(1) extra space?

Yes. The cyclic sort uses only i, j, a temporary variable and a counter. The problem allows the returned list to be excluded from the count, and it also allows the input to be modified. The method works in place.

Why does the hash set solution use O(n) space?

The set stores each distinct value in nums, which can be up to n values. Its size grows with the input, so it is O(n) space. The method is correct and linear, but it does not satisfy the follow-up.

Is there a Python gotcha on this problem?

Yes. Python passes the list by reference, so the swaps also change the caller's nums. If the caller still needs the original order, copy the list before calling the method. Values are at least 1, so nums[i] - 1 never becomes a negative index that Python would wrap around.

Asked at

See which companies ask this — Pro

Practise it