You have a set of integers 1, 2, ..., n
with one duplicate and one missing number. Your task is to identify the duplicate number and the missing number.
You are given an integer array nums
that represents this set and satisfies the following properties:
[1, n]
.Return an array containing the duplicate number and the missing number.
[1, n]
?
n
, where n
is the number of distinct integers in the set.1
to n
to find the missing number (appearing 0
times) and the duplicate number (appearing 2
times).Let’s implement the HashMap strategy first as it is more intuitive and easy to understand:
import java.util.HashMap;
public class SetMismatch {
public int[] findErrorNums(int[] nums) {
int n = nums.length;
HashMap<Integer, Integer> countMap = new HashMap<>();
// Populate the count map
for (int num : nums) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
int duplicate = -1, missing = -1;
// Determine the duplicate and missing numbers
for (int i = 1; i <= n; i++) {
if (countMap.getOrDefault(i, 0) == 0) {
missing = i;
} else if (countMap.get(i) == 2) {
duplicate = i;
}
}
return new int[] {duplicate, missing};
}
public static void main(String[] args) {
SetMismatch sm = new SetMismatch();
int[] nums = {1, 2, 2, 4};
int[] result = sm.findErrorNums(nums);
System.out.println("Duplicate number: " + result[0]);
System.out.println("Missing number: " + result[1]);
}
}
1
to n
to find the duplicate and missing numbers.This solution is efficient and easy to understand. It leverages the properties of HashMaps to solve the problem with linear time complexity.
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?