PROBLEM LINK: Additional Number
Author: Rishabh Rathi
Tester: Rishabh Rathi
DIFFICULTY:
CAKEWALK
PREREQUISITES:
None
PROBLEM:
You are given two integer arrays − A and B. The first array has N elements, and the second array has N+1 elements.
The second array (B) contains all the elements of the first array (A) (not necessarily the same order) and 1 additional element.
You need to find the additional element present in B.
EXPLANATION:
As there is only 1 additional element, we can simply sort both the arrays and then check the additional element present in B.
For that, we can start iterating i from 1 to N (1 based indexing). For some i, if A[i] \neq B[i], it means that the additional element is B[i]. For first N elements, if there is no mismatch, then B[N+1] is the additional element.
Code (Python):
def solve(n, a, b):
a.sort()
b.sort()
for i in range(n):
if a[i] != b[i]:
return b[i]
return b[n]
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = solve(n, a, b)
print(ans)
ALTERNATIVE EXPLANATION:
This question can also be solved using mathematics. To find the additional element, we can simply find the difference of sum of elements of B and sum of elements of A.
Code (Python):
def solve(a, b):
return sum(b) - sum(a)
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = solve(a, b)
print(ans)
Feel free to share your approach. In case of any doubt or anything is unclear, please ask it in the comments section. Any suggestions are welcome