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 All Numbers Disappeared in an Array INPUT Array nums (n=8, range [1,8]) 4 3 2 7 8 2 3 1 i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 Expected Range [1,n]: 1, 2, 3, 4, 5, 6, 7, 8 Find which numbers from [1,8] are missing in nums ALGORITHM STEPS Hash Set Approach 1 Create Hash Set Add all nums to a set Set = {4,3,2,7,8,1} (duplicates removed) 2 Iterate [1, n] Check each num 1 to 8 3 Check Set Membership Is num in hash set? 1 in Set? Yes 2 in Set? Yes 3 in Set? Yes 4 in Set? Yes 5 in Set? No 6 in Set? No 7 in Set? Yes 8 in Set? Yes 4 Collect Missing Add to result if not in set FINAL RESULT Numbers NOT in hash set: Missing Numbers 5, 6 Output Array: [5, 6] Verification: Present: 1,2,3,4,7,8 Missing: 5,6 OK - Correct! Key Insight: Hash Set provides O(1) lookup time. We add all array elements to a set, then iterate through [1,n] checking if each number exists. Time: O(n), Space: O(n). For O(1) space, use index marking technique where we negate values at indices corresponding to seen numbers, then find positive indices. TutorialsPoint - Find All Numbers Disappeared in an Array | Hash Set Approach
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