1
to n
(inclusive), where n
is the length of the array?The problem requires finding all numbers in the range [1, n]
that are missing from the given array. Given that the array might contain duplicates but the values are bound within 1
to n
, we can use the properties of the array to mark which numbers are present.
Here’s a step-by-step strategy to achieve the solution efficiently:
def findDisappearedNumbers(nums):
# Mark numbers present in the array by marking the index corresponding to those numbers as negative
for num in nums:
index = abs(num) - 1
if nums[index] > 0:
nums[index] = -nums[index]
# Collect the indices + 1 where the values are still positive
result = []
for i in range(len(nums)):
if nums[i] > 0:
result.append(i + 1)
return result
This strategy effectively finds the missing numbers by leveraging the properties of the input array, ensuring an efficient and concise solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?