Sponsored
Sponsored
This approach uses the mathematical properties of numbers from 1 to n to determine the duplicate and missing numbers. Calculate the expected sum of numbers from 1 to n. Then, iterate through the array to find the actual sum of numbers and the sum of squares. By using these properties and equations, derive the duplicate and missing numbers.
Time Complexity: O(n), as we iterate through the input array three times.
Space Complexity: O(1), since we use a constant amount of space for variables.
1function findErrorNums(nums) {
2 const n = nums.length;
3 const sumN = n * (n + 1) / 2;
4 const sumNum = nums.reduce((a, b) => a + b, 0);
5 const sumSquareN = n * (n + 1) * (2 * n + 1) / 6;
6 const sumSquareNum = nums.reduce((a, b) => a + b * b, 0);
7 const sumDiff = sumN - sumNum;
8 const squareSumDiff = sumSquareN - sumSquareNum;
9 const sumMD = squareSumDiff / sumDiff;
10 const missing = (sumMD + sumDiff) / 2;
11 const duplicate = sumMD - missing;
12 return [duplicate, missing];
13}
This JavaScript function follows the same line of reasoning as the Python solution. It calculates the difference of sums and sums of squares, then derives the missing and duplicate values.
In this approach, utilize a hashmap to count the occurrences of each number. Iterate over the numbers from 1 to n and use the occurrence count to identify the duplicated and missing numbers.
Time Complexity: O(n), where n is the length of nums, due to two iterations over the array.
Space Complexity: O(n), for storing the counts in a hashmap.
1using System.Collections.Generic;
2
3public class Solution {
4 public int[] FindErrorNums(int[] nums) {
5 Dictionary<int, int> countMap = new Dictionary<int, int>();
foreach (var num in nums) {
if (countMap.ContainsKey(num))
countMap[num]++;
else
countMap[num] = 1;
}
int duplicate = -1, missing = -1;
for (int i = 1; i <= nums.Length; i++) {
if (countMap.ContainsKey(i)) {
if (countMap[i] == 2) duplicate = i;
} else {
missing = i;
}
}
return new int[] { duplicate, missing };
}
}
This C# solution also uses a dictionary to track occurrences of numbers. Similar to the Java solution, it checks the presence and count of each number.