Find All Numbers Disappeared In An Array
To solve this coding challenge, we need to identify and return all the numbers in the range [1, n] that are missing from the given array
. The array
has a length of
, and every element in
is an integer within the range [1, n]. We need to find a way to achieve this with O(n) runtime without using extra space, although the returned list does not count as extra space per the problem constraints.
nums
nums
n
nums
Explanation
Here's a detailed breakdown of how we can approach this problem:- Understand the Problem Constraints :
-
We have an array
nums
n
-
Every element in
nums
n
- Objective :
-
Identify all the integers from 1 to
n
nums
- Return these missing integers in a list.
- Optimal Strategy :
- We need to achieve this in O(n) runtime and with constant extra space.
- A classic approach to achieve O(n) runtime involves modifying the original array in place to mark the presence of elements.
- Marking Presence :
- For each element in the array, the index corresponding to the value (reduced by 1) can be used to mark its presence.
- To avoid using extra space, we can mark an element as seen by making the value at the corresponding index negative (only if it’s not already negative).
-
This marks the index
i
i+1
- Identifying Missing Numbers :
-
After marking all present elements, any index
i
i+1
- Implementation Steps :
- Iterate over each element in the array and use its absolute value to determine the index to mark as visited.
- Iterate over the array again to collect all indices that have positive values; these indices correspond to missing numbers.
- Initialization :
-
Define a function
findDisappearedNumbers
nums
-
Calculate the length of
nums
array_length
- Marking Phase :
-
Iterate over each element in
nums
-
For each element, compute
corresponding_index
abs(element) - 1
-
Check if
nums[corresponding_index]
-
If it is positive, negate the value at
nums[corresponding_index]
- Collection Phase :
-
Initialize an empty list
missing_numbers
-
Iterate over the range from 0 to
array_length - 1
-
For each index
i
nums[i]
-
If
nums[i]
i + 1
missing_numbers
- Final Output :
-
Return the
missing_numbers
n
nums
Pseudocode with Comments
# Step 1: Define the function to find disappeared numbers
function findDisappearedNumbers(nums):
# Get the length of the input array
array_length = length(nums)
# Step 2: Mark presence of each number
for each element in nums:
# Calculate the corresponding index
corresponding_index = absolute_value(element) - 1
# Mark the presence by making the value at corresponding_index negative
if nums[corresponding_index] > 0:
nums[corresponding_index] = -nums[corresponding_index]
# Step 3: Collect the missing numbers
missing_numbers = []
for i in range(array_length):
# If the value at index i is positive, it means number i+1 is missing
if nums[i] > 0:
missing_numbers.append(i + 1)
# Step 4: Return the list of missing numbers
return missing_numbers