Find the missing element between two arrays in Python

The challenge

Given two integer arrays where the second array is a shuffled duplicate of the first array with one element missing, find the missing element.

Please note, there may be duplicates in the arrays, so checking if a numerical value exists in one and not the other is not a valid solution.

find_missing([1, 2, 2, 3], [1, 2, 3]) => 2
find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]) => 8

The first array will always have at least one element.

Test cases

Test.it("Basic tests")

Test.assert_equals(find_missing([1, 2, 3], [1, 3]), 2)
Test.assert_equals(find_missing([6, 1, 3, 6, 8, 2], [3, 6, 6, 1, 2]), 8)
Test.assert_equals(find_missing([7], []), 7)
Test.assert_equals(find_missing([4, 3, 3, 61, 8, 8], [8, 61, 8, 3, 4]), 3)
Test.assert_equals(find_missing([0, 0, 0, 0, 0], [0, 0, 0, 0]), 0)

The solution in Python

Option 1 (using sum):

def find_missing(arr1, arr2):
    return sum(arr1)-sum(arr2)

Option 2 (using reduce):

from functools import reduce
from operator import xor

def find_missing(xs, ys):
    return reduce(xor, xs, 0) ^ reduce(xor, ys, 0)

Option 3 (removing from list):

def find_missing(a, b):
    for x in b:
        a.remove(x)

    return a[0]
Tags:
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments