
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Lost Element from a Duplicated Array in Python
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
return A[0];
-
if A[0] is not same as B[0], then
return A[0]
low := 0, high := N - 1
-
while low < high, do
mid :=(low + high) / 2
-
if A[mid] is same as B[mid], then
low := mid
-
otherwise,
high := mid
-
if low is same as high - 1, then
come out from the loop
return A[high]
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)
-
otherwise,
return "Not found"
Example
Let us see the following implementation to get better understanding −
def solve(A, B, N): if N == 1: return A[0]; if A[0] != B[0]: return A[0] 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))
Input
[2, 5, 6, 8, 10], [5, 6, 8, 10]
Output
2