Python Set difference to find lost element from a duplicated array

Given two arrays which are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element. Examples:
Input: A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
Output: [1]
1 is missing from second array.
Input: A = [2, 3, 4, 5
B = 2, 3, 4, 5, 6]
Output: [6]
6 is missing from first array.
We have existing solution for this problem please refer Find lost element from a duplicated array. We can solve this problem quickly in python using Set difference logic. Approach is very simple, simply convert both lists in Set and perform A-B operation where len(A)>len(B).Â
Implementation:
Python3
# Function to find lost element from a duplicate# arrayÂ
def lostElement(A,B):         # convert lists into set    A = set(A)    B = set(B)Â
    # take difference of greater set with smaller    if len(A) > len(B):        print (list(A-B))    else:        print (list(B-A))Â
# Driver programif __name__ == "__main__":Â Â Â Â A = [1, 4, 5, 7, 9]Â Â Â Â B = [4, 5, 7, 9]Â Â Â Â lostElement(A,B) |
Output
[1]
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



