Find lost element from a duplicated array in Python

Finding a lost element from a duplicated array is a common problem where two arrays are identical except one element is missing from one of them. We need to identify which element is missing efficiently.

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.

Using Binary Search Approach

The most efficient approach uses binary search to find the missing element in O(log n) time complexity ?

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"

# Example usage
A = [2, 5, 6, 8, 10]
B = [5, 6, 8, 10]
print(get_missing_element(A, B))
2

Using Set Difference (Simple Approach)

For smaller arrays, we can use set operations to find the difference ?

def find_missing_simple(A, B):
    set_A = set(A)
    set_B = set(B)
    
    # Find element in A but not in B
    diff_A = set_A - set_B
    if diff_A:
        return list(diff_A)[0]
    
    # Find element in B but not in A
    diff_B = set_B - set_A
    if diff_B:
        return list(diff_B)[0]
    
    return "No missing element"

# Example usage
A = [2, 5, 6, 8, 10]
B = [5, 6, 8, 10]
print(find_missing_simple(A, B))
2

Using XOR Operation

XOR approach works because x ^ x = 0 and x ^ 0 = x, so duplicate elements cancel out ?

def find_missing_xor(A, B):
    result = 0
    
    # XOR all elements in both arrays
    for num in A:
        result ^= num
    
    for num in B:
        result ^= num
    
    return result

# Example usage
A = [2, 5, 6, 8, 10]
B = [5, 6, 8, 10]
print(find_missing_xor(A, B))
2

Comparison of Methods

Method Time Complexity Space Complexity Best For
Binary Search O(log n) O(1) Sorted arrays
Set Difference O(n) O(n) Unsorted arrays
XOR Operation O(n) O(1) Memory-efficient solution

Conclusion

Use binary search for sorted arrays with O(log n) efficiency. For unsorted arrays, XOR operation provides O(1) space complexity, while set difference offers simplicity and readability.

Updated on: 2026-03-25T09:43:42+05:30

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements