15% off all plans & roadmaps Use code
See plansFind All Numbers Disappeared in an Array
- LeetCode 448
- Easy
- Array/Matrix Manipulation Patterns
- Array - Cyclic Sort
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.length1 <= n <= 10^51 <= nums[i] <= n
Constraints that matter
nup 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 valuevhas a home indexv - 1that 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
nvalues, so the output does not count toward extra space.
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.
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
- Set
nto the length ofnumsand create an empty result list. - For each candidate
vfrom 1 ton, set afoundflag to false. - Scan every element
xofnums. Ifxequalsv, setfoundto true and stop the scan. - If
foundis still false after the scan, appendvto the result. - 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
| Time | O(n^2) |
|---|---|
| Space | O(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 resultApproach 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
- Set
nto the length ofnums. - Insert every value of
numsinto a hash set. Duplicates collapse into one entry. - For each
vfrom 1 ton, check whethervis in the set. - If
vis not in the set, append it to the result. - 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
| Time | O(n) |
|---|---|
| Space | O(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 resultThe 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 infographicSolution pattern
Array - Cyclic Sort
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
- Set
ito 0 andnto the length ofnums. - While
iis less thann, computej = nums[i] - 1, the home slot of the value ati. - If
nums[i]differs fromnums[j], swap them and leaveiunchanged so the new value atigets checked. - Otherwise the value is home, or a duplicate already sits in its home, so increase
iby 1. - After the loop, scan
kfrom 0 ton - 1. Wherevernums[k]is notk + 1, appendk + 1to the result. - 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.
| Step | i | nums[i] | Home j | nums[j] | Action | Array after step |
|---|---|---|---|---|---|---|
| 1 | 0 | 10 | 9 | 7 | swap | [7, 2, 5, 10, 9, 1, 1, 4, 3, 10] |
| 2 | 0 | 7 | 6 | 1 | swap | [1, 2, 5, 10, 9, 1, 7, 4, 3, 10] |
| 3 | 0 | 1 | 0 | 1 | equal, i to 1 | unchanged |
| 4 | 1 | 2 | 1 | 2 | equal, i to 2 | unchanged |
| 5 | 2 | 5 | 4 | 9 | swap | [1, 2, 9, 10, 5, 1, 7, 4, 3, 10] |
| 6 | 2 | 9 | 8 | 3 | swap | [1, 2, 3, 10, 5, 1, 7, 4, 9, 10] |
| 7 | 2 | 3 | 2 | 3 | equal, i to 3 | unchanged |
| 8 | 3 | 10 | 9 | 10 | equal, i to 4 | unchanged |
| 9 | 4 | 5 | 4 | 5 | equal, i to 5 | unchanged |
| 10 | 5 | 1 | 0 | 1 | equal, i to 6 | unchanged |
| 11 | 6 | 7 | 6 | 7 | equal, i to 7 | unchanged |
| 12 | 7 | 4 | 3 | 10 | swap | [1, 2, 3, 4, 5, 1, 7, 10, 9, 10] |
| 13 | 7 | 10 | 9 | 10 | equal, i to 8 | unchanged |
| 14 | 8 | 9 | 8 | 9 | equal, i to 9 | unchanged |
| 15 | 9 | 10 | 9 | 10 | equal, i to 10, loop ends | unchanged |
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
| Time | O(n) |
|---|---|
| Space | O(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 resultCommon 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 againstnums[j], the value already in the home slot, and advance when they match. - Writing
ifinstead of a loop that stays oni. Afterif (nums[i] != nums[j]) swap; i++, the value pulled into positioniis never checked. Keepifixed after a swap and advance only when the slot is settled. - Checking
nums[k] != kin the final scan. Values run from 1 to n, so the home value of indexkisk + 1. Usenums[k] != k + 1. - Running the final scan before the
whileloop 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
ArrayListfrom the Java method. The starter signature returnsint[], 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]withn = 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.numsalready equal to[1, 2, ..., n]: no swaps happen and the result is [].n = 100000with 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-upsFind 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
Related problems
- Missing Number · same technique: Array - Cyclic Sort
- Find the Duplicate Number · same technique: Array - Cyclic Sort
- Find All Duplicates in an Array · same technique: Array - Cyclic Sort
- First Missing Positive · same technique: Array - Cyclic Sort
- Two Sum · same pattern: Array/Matrix Manipulation Patterns
- Contains Duplicate · same pattern: Array/Matrix Manipulation Patterns
- Happy Number · same pattern: Array/Matrix Manipulation Patterns
- Valid Anagram · same pattern: Array/Matrix Manipulation Patterns
- Plus One · same pattern: Array/Matrix Manipulation Patterns
- Linked List Cycle · same pattern: Array/Matrix Manipulation Patterns