You’re given an initial array of n
integers and another array of n+1
integers which contains all the original integers plus one additional integer. Write a function to find the additional integer that was added.
What kind of values can the integers in the array take? They can be any valid integer values, both positive and negative, and can also include zero.
Are the integers in the arrays unique? Yes, all integers in the initial array are unique.
Can we assume the arrays are valid (i.e. the second array always has exactly one more integer)? Yes, you can assume the input is always valid as per the problem statement.
Is there any specific order for the output? No, just return the additional integer.
To find the additional integer, several strategies can be used, such as sorting the arrays and comparing, using a hash map to count occurrences, etc. However, a more optimal way is to use the properties of sums:
This approach is optimal in terms of both time and space complexities.
Here is the Python implementation of the described approach:
def find_added_integer(original, extended):
# Calculate the sum of the original and the extended arrays
sum_original = sum(original)
sum_extended = sum(extended)
# The difference will be the added integer
added_integer = sum_extended - sum_original
return added_integer
# Example Usage:
original = [3, 1, 2, 4]
extended = [3, 1, 2, 4, 5]
print(find_added_integer(original, extended)) # Output: 5
original
array.extended
array.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?