Leetcode 2965. Find Missing and Repeated Values
You are given an array nums
containing n
integers where the integers are in the range [1, n]
. One number appears once (missing number) and another number appears twice (repeated number). Your task is to find these two numbers.
nums
we should expect?[1, n]
?Assuming it’s a typical LeetCode medium level problem:
n
can be at most (10^4).[1, n]
.vector
of integers in C++.We need to solve two parts of the problem: identifying the missing number and the repeated number. Let’s utilize the properties of the sum and squared sum of the first n
natural numbers for this.
n
natural numbers: ( S = \frac{n(n + 1)}{2} )n
natural numbers: ( P = \frac{n(n + 1)(2n + 1)}{6} )nums
:
sum(nums)
be the sum of elements in the array.sum(nums^2)
be the sum of the squares of elements in the array.By solving these equations, we can find the repeated and missing values.
#include <vector>
#include <iostream>
using namespace std;
vector<int> findErrorNums(vector<int>& nums) {
long long n = nums.size();
long long sum_n = n * (n + 1) / 2;
long long sum_n2 = n * (n + 1) * (2 * n + 1) / 6;
long long sum_nums = 0, sum_nums2 = 0;
for (int num : nums) {
sum_nums += num;
sum_nums2 += (long long)num * num;
}
long long diff = sum_nums - sum_n; // repeated - missing
long long sq_diff = sum_nums2 - sum_n2; // repeated^2 - missing^2
// Solving the equations:
// repeated + missing = sq_diff / diff
long long sum = sq_diff / diff;
int repeated = (diff + sum) / 2;
int missing = sum - repeated;
return {repeated, missing};
}
int main() {
vector<int> nums = {1, 2, 2, 4};
vector<int> result = findErrorNums(nums);
cout << "Repeated: " << result[0] << ", Missing: " << result[1] << endl;
return 0;
}
This method leverages mathematical properties and is efficient for the given problem constraints.
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?