Find All Numbers Disappeared in an Array - Problem

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
💡 Note: The array has length 8, so numbers should be in range [1,8]. Numbers 1,2,3,4,7,8 are present (with duplicates). Numbers 5 and 6 are missing.
Example 2 — Single Missing
$ Input: nums = [1,1]
Output: [2]
💡 Note: Array length is 2, so range is [1,2]. Number 1 appears twice, number 2 is missing.
Example 3 — No Missing Numbers
$ Input: nums = [1,2,3]
Output: []
💡 Note: All numbers from 1 to 3 are present, so no numbers are missing.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 104
  • 1 ≤ nums[i] ≤ n

Visualization

Tap to expand
Find Missing Numbers: Input [4,3,2,7,8,2,3,1] → Output [5,6]Input Array (length = 8):43278231Expected Range [1, 2, 3, 4, 5, 6, 7, 8]:12345678Missing Numbers:56Result: [5, 6]
Understanding the Visualization
1
Input Analysis
Array of length n with numbers in range [1,n]
2
Key Insight
Use array indices as hash table to track presence
3
Output
List of missing numbers from the expected range
Key Takeaway
🎯 Key Insight: Since numbers are in range [1,n], we can use array indices as a hash table to mark presence without extra space
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
320.0K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen