Find All Numbers Disappeared in an Array - Problem
You're given an array nums containing n integers where each number is guaranteed to be in the range [1, n]. Your task is to find all the missing numbers from this range that don't appear in the array.

Think of it like a roll call - you have a list of student IDs from 1 to n, but some students are absent. You need to identify which student numbers are missing from your attendance list.

Goal: Return an array containing all integers in the range [1, n] that are not present in the input array.

Example: If nums = [4,3,2,7,8,2,3,1] and n = 8, the missing numbers are [5, 6] because all numbers from 1 to 8 should be present, but 5 and 6 are nowhere to be found.

Input & Output

example_1.py โ€” Basic Case
$ Input: [4,3,2,7,8,2,3,1]
โ€บ Output: [5,6]
๐Ÿ’ก Note: The array contains numbers in range [1,8]. Numbers 1,2,3,4,7,8 are present (some appear multiple times), but 5 and 6 are completely missing.
example_2.py โ€” Single Missing
$ Input: [1,1]
โ€บ Output: [2]
๐Ÿ’ก Note: Array length is 2, so we expect numbers [1,2]. Number 1 appears twice, but number 2 is missing.
example_3.py โ€” All Present
$ Input: [1,2,3,4]
โ€บ Output: []
๐Ÿ’ก Note: All numbers from 1 to 4 are present in the array, so no numbers are missing.

Constraints

  • n == nums.length
  • 1 โ‰ค n โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค n
  • Follow up: Could you do it without extra space and in O(n) runtime?

Visualization

Tap to expand
The Missing Students ProblemClassroom with 8 desks (positions 1-8):Student 1โœ“ PresentStudent 2โœ“ PresentStudent 3โœ“ PresentStudent 4โœ“ PresentStudent 5โœ— AbsentStudent 6โœ— AbsentStudent 7โœ“ PresentStudent 8โœ“ PresentMessy attendance list: [4,3,2,7,8,2,3,1]43278231Some duplicates, some missing!Smart Solution: Use array positions as attendance markers๐Ÿ‘ฉโ€๐Ÿซ"I'll mark each student's desk when I see their number!""Missing students will have unmarked desks""This way I use O(1) extra space!"Result: Students 5 and 6 are absent56โ† Missing numbers found efficiently!
Understanding the Visualization
1
The Messy List
Your attendance shows: [4,3,2,7,8,2,3,1] - some duplicates, some missing
2
Smart Marking
Use the list positions as markers - mark position (number-1) as 'present' by making it negative
3
Find the Absent
After marking, positions that remain positive indicate missing students
Key Takeaway
๐ŸŽฏ Key Insight: When numbers are in range [1,n] and you have n positions, you can use the array itself as a hash table by leveraging the sign bit to mark presence!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
32.9K Views
High Frequency
~15 min Avg. Time
1.2K 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