Leetcode 3131. Find the Integer Added to Array I
You are given an integer array original and another integer array added which is identical to original with exactly one integer added to it. Your task is to find the integer that was added to original to get added.
original array?
original array?
original will be at least 1 and at most 10^5.int type, which is -2^31 to 2^31-1.added and the sum of original will be the extra integer.original and added. The element which has a higher count in added is the one that was added.We will implement the first approach because it is simpler and has better performance characteristics for this problem size.
public class FindAddedNumber {
public int findAddedNumber(int[] original, int[] added) {
int sumOriginal = 0;
for (int num : original) {
sumOriginal += num;
}
int sumAdded = 0;
for (int num : added) {
sumAdded += num;
}
return sumAdded - sumOriginal;
}
public static void main(String[] args) {
FindAddedNumber sol = new FindAddedNumber();
int[] original = {4, 1, 3};
int[] added = {4, 1, 3, 7};
System.out.println(sol.findAddedNumber(original, added)); // Output: 7
}
}
O(n) time, where n is the number of elements in the original array (since the added array is n+1 elements).O(1) since we are using a few extra variables but not any additional data structures that scale with input size.This solution is efficient and straightforward 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?