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.
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 <= 1051 <= nums[i] <= n
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.
This approach uses the properties of the array and its indices to track missing numbers. By iterating through the array and using the values to mark the corresponding indices, we can identify which indices were never marked and thus determine the missing numbers.
Steps:
nums.This C solution implements index marking by negating the values at positions corresponding to the numbers seen in the array. It iterates over the array twice: first to mark visited numbers and second to collect those which are still positive, indicating those numbers are missing.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) - where n is the number of elements in the array because we are iterating over the array twice.
Space Complexity: O(1) - as no additional data structure is used apart from the output list and input array is modified in-place.
In this approach, we utilize a set to only store unique numbers from 1 to n that appear in the input array. By comparing this set to the complete range of numbers, we can directly determine those not present in the input.
Steps:
nums.In this solution, a boolean array acts as a set storing flags for numbers detected in the input. Subsequent traversal is made to seek indices flagged false, representing the missing numbers.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(n), due to use of additional boolean array to track presence of numbers.
| Approach | Complexity |
|---|---|
| Approach 1: Index Marking | Time Complexity: O(n) - where n is the number of elements in the array because we are iterating over the array twice. |
| Approach 2: Set-Based Method | Time Complexity: O(n) |
Find All Numbers Disappeared in an Array - Leetcode 448 - Python • NeetCode • 53,986 views views
Watch 9 more video solutions →Practice Find All Numbers Disappeared in an Array with our built-in code editor and test cases.
Practice on FleetCode