The Wayback Machine - https://web.archive.org/web/20230512160723/https://www.geeksforgeeks.org/python-list-comprehension-find-pair-given-sum-two-arrays/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python List Comprehension to find pair with given sum from two arrays

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. 

Examples:

Input :  arr1 = [-1, -2, 4, -6, 5, 7]
         arr2 = [6, 3, 4, 0]  
         x = 8
Output : [(5, 3), (4, 4)]
         

Input : arr1 = [1, 2, 4, 5, 7] 
        arr2 = [5, 6, 3, 4, 8]  
        x = 9
Output : [(1, 8), (4, 5), (5, 4)]

We have existing solution for this problem please refer Given two unsorted arrays, find all pairs whose sum is x link. We can solve this problem quickly in python using List comprehension. Approach is very simple, we will consider all those pairs for which if k lies in arr2 then x-k should lie in arr1, so pair will be (x-k,k). 

Implementation:

Python3




# Function to find all pairs whose sum is x in
# two arrays
 
def allPairs(arr1,arr2,x):
     
    # finds all pairs in two arrays
    # whose sum is x
    print ([(x-k,k) for k in arr2 if (x-k) in arr1])
 
# Driver program
if __name__ == "__main__":
    arr1 = [-1, -2, 4, -6, 5, 7]
    arr2 = [6, 3, 4, 0]
    x = 8
    allPairs(arr1,arr2,x)

Output

[(5, 3), (4, 4)]

Complexity : O(n*n) 

My Personal Notes arrow_drop_up
Last Updated : 28 Jul, 2022
Like Article
Save Article
Similar Reads
Related Tutorials