Posts Find all pairs with a given sum (geeksforgeeks - SDE Sheet)
Post
Cancel

Find all pairs with a given sum (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X.

Note: All pairs should be printed in increasing order of u. For eg. for two pairs (u1,v1) and (u2,v2), if u1 < u2 then (u1,v1) should be printed first else second.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {

    public pair[] allPairs(long A[], long B[], long N, long M, long X) {

        // Create a HashSet to store elements from array A
        Set<Long> set = new HashSet<>();

        // Add elements from array A to the HashSet
        for(int i=0; i<N; i++)
            set.add(A[i]);

        // Create an ArrayList to store pairs that satisfy the condition
        List<pair> list = new ArrayList<>();

        // Iterate through array B
        for(int i=0; i<M; i++){

            // Check if there exists an element in array A such that their sum equals X
            if(set.contains(X-B[i])){
                // If such an element exists, add the pair (X-B[i], B[i]) to the list
                list.add(new pair(X-B[i], B[i]));
            }
        }

        // Convert the list to an array of pairs
        pair[] res = new pair[list.size()];
        for(int i=0; i<list.size(); i++)
            res[i] = list.get(i);

        // Sort the array of pairs in increasing order of the first element of each pair
        Arrays.sort(res, (a, b) -> (int) a.first - (int) b.first);

        return res;
    }

}
This post is licensed under CC BY 4.0 by the author.