Find All Numbers Disappeared in an Array - Problem
You're given an 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 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code