Leetcode 3131. Find the Integer Added to Array I
Given an integer array nums, find the integer that was added to the array. Initially, the array consists of the numbers from 1 to n, but one number has been added to the array. Return the integer that was added to the array.
Example:
Input: nums = [4, 1, 3, 2, 6, 5, 7, 8]
Output: 6
nums
?
n
.n
?
To solve this problem efficiently:
Calculate the expected sum of the first n
natural numbers using the formula:
[
\text{sum}_\text{expected} = \frac{n \cdot (n + 1)}{2}
]
Calculate the sum of all elements present in the nums
array:
[
\text{sum}_\text{actual}
]
The integer that was added will be the difference: [ \text{added\ integer} = \text{sum}\text{actual} - \text{sum}\text{expected} ]
#include <vector>
#include <numeric> // for accumulate function
int findAddedInteger(const std::vector<int>& nums) {
int n = nums.size() - 1;
int sum_expected = n * (n + 1) / 2;
int sum_actual = std::accumulate(nums.begin(), nums.end(), 0);
return sum_actual - sum_expected;
}
int main() {
std::vector<int> nums = {4, 1, 3, 2, 6, 5, 7, 8};
int result = findAddedInteger(nums);
std::cout << "The added integer is: " << result << std::endl;
return 0;
}
The time complexity of this solution is O(n), where n
is the size of the array minus 1. This is because:
std::accumulate
takes linear time, i.e., O(n + 1).The space complexity is O(1) as we are using a fixed amount of extra space regardless of the input size.
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?