Skip to content
Related Articles
Find pairs with given sum such that elements of pair are in different rows
• Difficulty Level : Medium
• Last Updated : 25 May, 2021

Given a matrix of distinct values and a sum. The task is to find all the pairs in a given matrix whose summation is equal to the given sum. Each element of a pair must be from different rows i.e; the pair must not lie in the same row.

Examples:

```Input : mat = {{1, 3, 2, 4},
{5, 8, 7, 6},
{9, 10, 13, 11},
{12, 0, 14, 15}}
sum = 11
Output: (1, 10), (3, 8), (2, 9), (4, 7), (11, 0) ```

Method 1 (Simple)
A simple solution for this problem is to, one by one, take each element of all rows and find pairs starting from the next immediate row in the matrix. The time complexity for this approach will be O(n4).

Method 2 (Use Sorting) within

• Sort all the rows in ascending order. The time complexity for this preprocessing will be O(n2 logn).
• Now we will select each row one by one and find pair elements in the remaining rows after the current row.
• Take two iterators, left and right. left iterator points left corner of the current i’th row and right iterator points right corner of the next j’th row in which we are going to find a pair of elements.
• If mat[i][left] + mat[j][right] < sum then left++ i.e; move in i’th row towards the right corner, otherwise right++ i.e; move in j’th row towards the left corner.

## C++

 `// C++ program to find a pair with given sum such that``// every element of pair is in different rows.``#include``using` `namespace` `std;` `const` `int` `MAX = 100;` `// Function to find pair for given sum in matrix``// mat[][] --> given matrix``// n --> order of matrix``// sum --> given sum for which we need to find pair``void` `pairSum(``int` `mat[][MAX], ``int` `n, ``int` `sum)``{``    ``// First sort all the rows in ascending order``    ``for` `(``int` `i=0; i=0)``            ``{``                ``if` `((mat[i][left] + mat[j][right]) == sum)``                ``{``                    ``cout << ``"("` `<< mat[i][left]``                         ``<< ``", "``<< mat[j][right] << ``"), "``;``                    ``left++;``                    ``right--;``                ``}``                ``else``                ``{``                    ``if` `((mat[i][left] + mat[j][right]) < sum)``                        ``left++;``                    ``else``                        ``right--;``                ``}``            ``}``        ``}``    ``}``}` `// Driver program to run the case``int` `main()``{``    ``int` `n = 4, sum = 11;``    ``int` `mat[][MAX] = {{1, 3, 2, 4},``                      ``{5, 8, 7, 6},``                      ``{9, 10, 13, 11},``                      ``{12, 0, 14, 15}};``    ``pairSum(mat, n, sum);``    ``return` `0;``}`

## Java

 `// Java program to find a pair with``// given sum such that every element``// of pair is in different rows.``import` `java.util.Arrays;``class` `GFG {``static` `final` `int` `MAX = ``100``;` `// Function to find pair for given sum in``// matrix mat[][] --> given matrix``// n --> order of matrix``// sum --> given sum for which we need to find pair``static` `void` `pairSum(``int` `mat[][], ``int` `n, ``int` `sum) {``    ` `    ``// First sort all the rows in ascending order``    ``for` `(``int` `i = ``0``; i < n; i++)``    ``Arrays.sort(mat[i]);` `    ``// Select i'th row and find pair for element in i'th``    ``// row in j'th row whose summation is equal to given sum``    ``for` `(``int` `i = ``0``; i < n - ``1``; i++) {``        ``for` `(``int` `j = i + ``1``; j < n; j++) {``            ``int` `left = ``0``, right = n - ``1``;``            ``while` `(left < n && right >= ``0``) {``                ``if` `((mat[i][left] + mat[j][right]) == sum) {``                ``System.out.print(``"("` `+ mat[i][left] + ``", "` `+``                                     ``mat[j][right] + ``"), "``);``                ``left++;``                ``right--;``                ``}``                ``else` `{``                    ``if` `((mat[i][left] + mat[j][right]) < sum)``                        ``left++;``                    ``else``                        ``right--;``                ``}``            ``}``        ``}``    ``}``}` `// Driver code``public` `static` `void` `main(String[] args) {``    ``int` `n = ``4``, sum = ``11``;``    ``int` `mat[]``        ``[] = {{``1` `,  ``3``,  ``2``,  ``4``},``              ``{``5` `,  ``8``,  ``7``,  ``6``},``              ``{``9` `, ``10``, ``13``, ``11``},``              ``{``12``,  ``0``, ``14``, ``15``}};``    ``pairSum(mat, n, sum);``}``}``// This code is contributed by Anant Agarwal.`

## Python 3

 `# Python 3 program to find a pair with``# given sum such that every element of``# pair is in different rows.``MAX` `=` `100` `# Function to find pair for given``# sum in matrix mat[][] --> given matrix``# n --> order of matrix``# sum --> given sum for which we``# need to find pair``def` `pairSum(mat, n, ``sum``):` `    ``# First sort all the rows``    ``# in ascending order``    ``for` `i ``in` `range``(n):``        ``mat[i].sort()` `    ``# Select i'th row and find pair for``    ``# element in i'th row in j'th row``    ``# whose summation is equal to given sum``    ``for` `i ``in` `range``(n ``-` `1``):``        ``for` `j ``in` `range``(i ``+` `1``, n):``            ``left ``=` `0``            ``right ``=` `n ``-` `1``            ``while` `(left < n ``and` `right >``=` `0``):``                ``if` `((mat[i][left] ``+` `mat[j][right]) ``=``=` `sum``):``                    ``print``( ``"("``, mat[i][left],``                           ``", "``, mat[j][right], ``"), "``,``                                            ``end ``=` `" "``)``                    ``left ``+``=` `1``                    ``right ``-``=` `1``                ` `                ``else``:``                    ``if` `((mat[i][left] ``+``                         ``mat[j][right]) < ``sum``):``                        ``left ``+``=` `1``                    ``else``:``                        ``right ``-``=` `1` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:``    ``n ``=` `4``    ``sum` `=` `11``    ``mat ``=` `[[``1``, ``3``, ``2``, ``4``],``           ``[``5``, ``8``, ``7``, ``6``],``           ``[``9``, ``10``, ``13``, ``11``],``           ``[``12``, ``0``, ``14``, ``15``]]``    ``pairSum(mat, n, ``sum``)` `# This code is contributed``# by ChitraNayal`

## Javascript

 ``

Output:

`(1, 10), (3, 8), (2, 9), (4, 7), (11, 0)`

Time complexity : O(n2logn + n^3)
Auxiliary space : O(1)

Method 3 (Hashing)

1. Create an empty hash table and store all elements of the matrix in the hash as keys and their locations as values.
2. Traverse the matrix again to check for every element whether its pair exists in the hash table or not. If it exists, then compare row numbers. If row numbers are not the same, then print the pair.

## CPP

 `// C++ program to find pairs with given sum such``// the two elements of pairs are from different rows``#include``using` `namespace` `std;` `const` `int` `MAX = 100;` `// Function to find pair for given sum in matrix``// mat[][] --> given matrix``// n --> order of matrix``// sum --> given sum for which we need to find pair``void` `pairSum(``int` `mat[][MAX], ``int` `n, ``int` `sum)``{``    ``// Create a hash and store all elements of matrix``    ``// as keys, and row and column numbers as values``    ``unordered_map<``int``, pair<``int``, ``int``> > hm;``    ``for` `(``int` `i=0; i p = it->second;``                ``int` `row = p.first, col = p.second;` `                ``// If row number of pair is not same as current``                ``// row, then print it as part of result.``                ``// Second condition is there to make sure that a``                ``// pair is printed only once. ``                ``if` `(row != i && row > i)``                   ``cout << ``"("` `<< mat[i][j] << ``", "``                        ``<< mat[row][col] << ``"), "``;``            ``}``        ``}``    ``}``}` `// Driver program``int` `main()``{``    ``int` `n = 4, sum = 11;``    ``int` `mat[][MAX]= {{1, 3, 2, 4},``                     ``{5, 8, 7, 6},``                     ``{9, 10, 13, 11},``                     ``{12, 0, 14, 15}};``    ``pairSum(mat, n, sum);``    ``return` `0;``}`

## Java

 `// Java program to find pairs with given sum such``// the two elements of pairs are from different rows``import` `java.io.*;``import` `java.util.*;``class` `GFG``{` `  ``static` `int` `MAX = ``100``;` `  ``// Function to find pair for given sum in matrix``  ``// mat[][] --> given matrix``  ``// n --> order of matrix``  ``// sum --> given sum for which we need to find pair``  ``static` `void` `pairSum(``int` `mat[][], ``int` `n, ``int` `sum)``  ``{` `    ``// Create a hash and store all elements of matrix``    ``// as keys, and row and column numbers as values``    ``Map> hm = ``new` `HashMap>();``    ``for` `(``int` `i = ``0``; i < n; i++)``    ``{``      ``for` `(``int` `j = ``0``; j < n; j++)``      ``{``        ``hm.put(mat[i][j], ``new` `ArrayList(Arrays.asList(i, j)) );``      ``}` `    ``}` `    ``// Traverse the matrix again to check for every``    ``// element whether its pair exists or not.``    ``for` `(``int` `i = ``0``; i < n; i++)``    ``{``      ``for` `(``int` `j = ``0``; j < n; j++)``      ``{` `        ``// Look for remaining sum in hash``        ``int` `remSum = sum - mat[i][j];` `        ``// If an element with value equal to remaining sum exists``        ``if``(hm.containsKey(remSum))``        ``{` `          ``// Find row and column numbers of element with``          ``// value equal to remaining sum.``          ``ArrayList p = hm.get(remSum);``          ``int` `row = p.get(``0``), col = p.get(``1``);` `          ``// If row number of pair is not same as current``          ``// row, then print it as part of result.``          ``// Second condition is there to make sure that a ``          ``// pair is printed only once.  ``          ``if` `(row != i && row > i)``          ``{``            ``System.out.print(``"("` `+ mat[i][j] + ``","` `+ mat[row][col] + ``"), "``);``          ``}``        ``}``      ``}``    ``}``  ``}` `  ``// Driver code``  ``public` `static` `void` `main (String[] args) {``    ``int` `n = ``4``, sum = ``11``;``    ``int``[][] mat = {{``1``, ``3``, ``2``, ``4``},``                   ``{``5``, ``8``, ``7``, ``6``},``                   ``{``9``, ``10``, ``13``, ``11``},``                   ``{``12``, ``0``, ``14``, ``15``}};``    ``pairSum(mat, n, sum);``  ``}``}` `// This code is contributed by avanitrachhadiya2155`

## C#

 `// C# program to find pairs with given sum such``// the two elements of pairs are from different rows``using` `System;``using` `System.Collections.Generic;``public` `class` `GFG``{   ` `  ``// Function to find pair for given sum in matrix``  ``// mat[][] --> given matrix``  ``// n --> order of matrix``  ``// sum --> given sum for which we need to find pair``  ``static` `void` `pairSum(``int``[,] mat, ``int` `n, ``int` `sum)``  ``{` `    ``// Create a hash and store all elements of matrix``    ``// as keys, and row and column numbers as values``    ``Dictionary<``int``,List<``int``>> hm = ``new` `Dictionary<``int``,List<``int``>>();``    ``for` `(``int` `i = 0; i < n; i++)``    ``{``      ``for` `(``int` `j = 0; j < n; j++)``      ``{``        ``hm.Add(mat[i,j],``new` `List<``int``>(){i,j});``      ``}``    ``}` `    ``// Traverse the matrix again to check for every``    ``// element whether its pair exists or not.``    ``for` `(``int` `i = 0; i < n; i++)``    ``{``      ``for` `(``int` `j = 0; j < n; j++)``      ``{` `        ``// Look for remaining sum in hash``        ``int` `remSum = sum - mat[i,j];` `        ``// If an element with value equal to remaining sum exists``        ``if``(hm.ContainsKey(remSum))``        ``{` `          ``// Find row and column numbers of element with``          ``// value equal to remaining sum.``          ``List<``int``> p = hm[remSum];``          ``int` `row = p, col = p;` `          ``// If row number of pair is not same as current``          ``// row, then print it as part of result.``          ``// Second condition is there to make sure that a ``          ``// pair is printed only once.  ``          ``if` `(row != i && row > i)``          ``{``            ``Console.Write(``"("` `+ mat[i, j] + ``","` `+ mat[row, col] + ``"), "``);``          ``}``        ``}``      ``}``    ``}``  ``}` `  ``// Driver code``  ``static` `public` `void` `Main (){``    ``int` `n = 4, sum = 11;``    ``int``[,] mat = {{1, 3, 2, 4},``                  ``{5, 8, 7, 6},``                  ``{9, 10, 13, 11},``                  ``{12, 0, 14, 15}};``    ``pairSum(mat, n, sum);``  ``}``}` `// This code is contributed by rag2127`

Output:

`(1, 10), (3, 8), (2, 9), (4, 7), (11, 0), `

One important thing is, when we traverse a matrix, a pair may be printed twice. To make sure that a pair is printed only once, we check if the row number of other elements picked from the hash table is more than the row number of the current element.
Time Complexity: O(n2) under the assumption that hash table inserts and search operations take O(1) time.

This article is contributed by Shashank Mishra ( Gullu ). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live

My Personal Notes arrow_drop_up