Suppose we have two arrays which are duplicates of each other except one element, so, one element from one of the given arrays is missing, we have to find that missing element.
So, if the input is like A = [2, 5, 6, 8, 10], B = [5, 6, 8, 10], then the output will be 2 as 2 is missing from second array.
To solve this, we will follow these steps −
Define a function solve() . This will take A, B, N
if N is same as 1, then
if A is not same as B, then
low := 0, high := N - 1
while low < high, do
mid :=(low + high) / 2
if A[mid] is same as B[mid], then
low := mid
high := mid
if low is same as high - 1, then
come out from the loop
From the main method, do the following −
M := size of A, N := size of B
if N is same as M-1, then
return solve(A, B, M)
otherwise when M is same as N-1, then
return solve(B, A, N)
return "Not found"
Let us see the following implementation to get better understanding −
def solve(A, B, N): if N == 1: return A; if A != B: return A low = 0 high = N - 1 while (low < high): mid = (low + high) / 2 if A[mid] == B[mid]: low = mid else: high = mid if low == high - 1: break return A[high] def get_missing_element(A, B): M = len(A) N = len(B) if N == M-1: return solve(A, B, M) elif M == N-1: return solve(B, A, N) else: return "Not found" A = [2, 5, 6, 8, 10] B = [5, 6, 8, 10] print(get_missing_element(A, B))
[2, 5, 6, 8, 10], [5, 6, 8, 10]