You have a set of integers s
, which originally contains all the numbers from 1
to n
. Unfortunately, due to some error, one of the numbers in s
got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums
representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
For example:
nums = [1,2,2,4]
, the output should be [2,3]
. The number 2 is duplicated, and the number 3 is missing.nums = [1,1]
, the output should be [1,2]
. The number 1 is duplicated, and the number 2 is missing.Write a function that efficiently finds these two numbers given the input array. Consider different approaches and analyze their time and space complexities. Discuss any edge cases that might affect the correctness of your solution.
You are given an array of integers nums
that originally contains all the numbers from 1 to n
. Due to an error, one number is duplicated, and another number is missing. The task is to find the duplicated number and the missing number.
A brute force solution involves iterating through the expected range of numbers from 1 to n
and checking for each number if it exists in the input array nums
. We can use nested loops or auxiliary data structures to accomplish this.
nums
.n
.i
, check if it exists in the set.
i
is the missing number.import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] findErrorNums(int[] nums) {
Set<Integer> seen = new HashSet<>();
int duplicate = -1;
int missing = -1;
int n = nums.length;
for (int num : nums) {
if (seen.contains(num)) {
duplicate = num;
}
seen.add(num);
}
for (int i = 1; i <= n; i++) {
if (!seen.contains(i)) {
missing = i;
break;
}
}
return new int[] {duplicate, missing};
}
}
An optimal solution can be achieved by using the input array itself as a hash table. This approach utilizes the indices of the array to store information about the presence or absence of numbers.
nums
.num
, take its absolute value and use it as an index. Negate the value at that index.
num
is the duplicate number.nums
again.class Solution {
public int[] findErrorNums(int[] nums) {
int duplicate = -1;
int missing = -1;
int n = nums.length;
// Find the duplicate number
for (int i = 0; i < n; i++) {
int index = Math.abs(nums[i]) - 1;
if (nums[index] < 0) {
duplicate = Math.abs(nums[i]);
} else {
nums[index] *= -1;
}
}
// Find the missing number
for (int i = 0; i < n; i++) {
if (nums[i] > 0) {
missing = i + 1;
break;
}
}
// Restore the array to its original state (optional)
for (int i = 0; i < n; i++) {
nums[i] = Math.abs(nums[i]);
}
return new int[] {duplicate, missing};
}
}