Find the missing element between two arrays in Python

0 min read 183 words

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:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags