You are given an integer array nums
of size n
containing each integer in the range [1, n]
inclusive, exactly once or twice. There is one repeated number and the rest appear exactly once. Your task is to find the repeated and the missing integers. Return them in the form of a list [repeated, missing]
.
[repeated, missing]
.To find the repeated and the missing values efficiently, we can use mathematical properties and iterative checks:
Here’s a method to achieve this:
nums
.x
, negate the value at index abs(x) - 1
.from typing import List
def findErrorNums(nums: List[int]) -> List[int]:
n = len(nums)
duplicate = -1
missing = -1
# Identify duplicate
for num in nums:
if nums[abs(num) - 1] < 0:
duplicate = abs(num)
else:
nums[abs(num) - 1] *= -1
# Identify missing
for i in range(n):
if nums[i] > 0:
missing = i + 1
return [duplicate, missing]
# Example usage
example = [4, 3, 6, 2, 1, 1]
print(findErrorNums(example)) # Output should be [1, 5]
O(n)
O(1)
This approach ensures that we can find the repeated and missing values efficiently with linear time complexity and constant space complexity by modifying the input array in place.
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?