Given an integer array nums
of length n
where all the integers of nums
are in the range [1, n]
and each integer appears once or twice, find all the integers that appear twice.
You should implement the solution with O(n) time complexity and use only constant extra space.
nums
apart from its length and range of values?Assuming no further constraints are given, let’s proceed to the strategy.
To achieve the requirements of O(n) time complexity and constant extra space, we can use the fact that the integers are in the range [1, n]
. This allows us to use the array itself for marking the visited elements.
Here is the approach in detail:
num
at index i
, calculate the index index = abs(num) - 1
and negate the value at nums[index]
.nums[index]
is already negative, it means the number abs(num)
is a duplicate.nums[index]
is negative, add abs(num)
to the result list.from typing import List
def findDuplicates(nums: List[int]) -> List[int]:
duplicates = []
for num in nums:
index = abs(num) - 1
if nums[index] < 0:
duplicates.append(abs(num))
else:
nums[index] = -nums[index]
# Optional: Restore the original array
# for i in range(len(nums)):
# nums[i] = abs(nums[i])
return duplicates
# Example usage
print(findDuplicates([4,3,2,7,8,2,3,1])) # Output: [2, 3]
print(findDuplicates([1,1,2])) # Output: [1]
print(findDuplicates([1])) # Output: []
nums
are done in place.This approach efficiently finds all duplicates in the list while adhering to the constraints of O(n) time complexity and constant extra space.
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?