Find pairs with given sum such that elements of pair are in different rows
Last Updated :
11 Sep, 2023
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[4][4] = {{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.
C++
#include <bits/stdc++.h>
using namespace std;
int pairSum(vector<vector< int > >& mat, int sum)
{
int m = mat.size();
int n = mat[0].size();
int count = 0;
for ( int i = 0; i < m; i++) {
for ( int j = i + 1; j < m; j++) {
for ( int k = 0; k < n; k++) {
for ( int l = 0; l < n; l++) {
if (mat[i][k] + mat[j][l] == sum) {
cout << "(" << mat[i][k] << ", "
<< mat[j][l] << "), " ;
}
}
}
}
}
return count;
}
int main()
{
int sum = 11;
vector<vector< int > > mat = { { 1, 3, 2, 4 },
{ 5, 8, 7, 6 },
{ 9, 10, 13, 11 },
{ 12, 0, 14, 15 } };
pairSum(mat, sum);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static int pairSum( int [][] mat, int sum)
{
int m = mat.length;
int n = mat[ 0 ].length;
int count = 0 ;
for ( int i = 0 ; i < m; i++) {
for ( int j = i + 1 ; j < m; j++) {
for ( int k = 0 ; k < n; k++) {
for ( int l = 0 ; l < n; l++) {
if (mat[i][k] + mat[j][l] == sum) {
System.out.print(
"(" + mat[i][k] + ", "
+ mat[j][l] + "), " );
}
}
}
}
}
return count;
}
public static void main(String[] args)
{
int sum = 11 ;
int [][] mat = { { 1 , 3 , 2 , 4 },
{ 5 , 8 , 7 , 6 },
{ 9 , 10 , 13 , 11 },
{ 12 , 0 , 14 , 15 } };
pairSum(mat, sum);
}
}
|
Python3
def pair_sum(mat, sum ):
count = 0
m = len (mat)
n = len (mat[ 0 ])
for i in range (m):
for j in range (i + 1 , m):
for k in range (n):
for l in range (n):
if mat[i][k] + mat[j][l] = = sum :
print (f "({mat[i][k]}, {mat[j][l]}), " )
return count
sum = 11
mat = [[ 1 , 3 , 2 , 4 ],
[ 5 , 8 , 7 , 6 ],
[ 9 , 10 , 13 , 11 ],
[ 12 , 0 , 14 , 15 ]]
pair_sum(mat, sum )
|
C#
using System;
using System.Linq;
class Program
{
static void Main( string [] args)
{
int [][] mat = new int [][] {
new int [] { 1, 3, 2, 4 },
new int [] { 5, 8, 7, 6 },
new int [] { 9, 10, 13, 11 },
new int [] { 12, 0, 14, 15 }
};
int sum = 11;
int count = 0;
for ( int i = 0; i < mat.Length; i++)
{
for ( int j = i + 1; j < mat.Length; j++)
{
for ( int k = 0; k < mat[i].Length; k++)
{
for ( int l = 0; l < mat[j].Length; l++)
{
if (mat[i][k] + mat[j][l] == sum)
{
Console.WriteLine( "(" + mat[i][k] + ", " + mat[j][l] + ")" );
count++;
}
}
}
}
}
}
}
|
Javascript
<script>
function pairSum(mat, sum){
m = mat.length;
n = mat[0].length;
count = 0;
for (let i = 0; i < m; i++) {
for (let j = i + 1; j < m; j++) {
for (let k = 0; k < n; k++) {
for (let l = 0; l < n; l++) {
if (mat[i][k] + mat[j][l] == sum) {
document.write( "(" , mat[i][k], ", " , mat[j][l], "), " );
}
}
}
}
}
return count;
}
let sum = 11;
let mat = [[ 1, 3, 2, 4 ],
[5, 8, 7, 6 ],
[ 9, 10, 13, 11 ],
[12, 0, 14, 15 ]];
pairSum(mat, sum);
</script>
|
Output
(3, 8), (4, 7), (1, 10), (2, 9), (11, 0),
Time Complexity: O(m2*n2), where m and n are the numbers of rows and columns of the given matrix respectively.
Auxiliary Space: O(1)
Method 2 (Use Sorting)
- 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
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
const int MAX = 100;
void pairSum( int mat[][MAX], int n, int sum)
{
for ( int i=0; i<n; i++)
sort(mat[i], mat[i]+n);
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)
{
cout << "(" << mat[i][left]
<< ", " << mat[j][right] << "), " ;
left++;
right--;
}
else
{
if ((mat[i][left] + mat[j][right]) < sum)
left++;
else
right--;
}
}
}
}
}
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
import java.util.Arrays;
class GFG {
static final int MAX = 100 ;
static void pairSum( int mat[][], int n, int sum) {
for ( int i = 0 ; i < n; i++)
Arrays.sort(mat[i]);
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--;
}
}
}
}
}
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);
}
}
|
Python 3
MAX = 100
def pairSum(mat, n, sum ):
for i in range (n):
mat[i].sort()
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
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 )
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static void pairSum( int [,]mat, int n, int sum) {
for ( int i = 0; i < n; i++)
{
List< int > l = new List< int >();
for ( int j = 0; j<n;j++)
{
l.Add(mat[i,j]);
}
l.Sort();
for ( int j = 0; j<n;j++)
{
mat[i,j] = l[j];
}
}
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) {
Console.Write( "(" + mat[i,left] + ", " +
mat[j,right] + "), " );
left++;
right--;
}
else {
if ((mat[i,left] + mat[j,right]) < sum)
left++;
else
right--;
}
}
}
}
}
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);
}
}
|
Javascript
<script>
let MAX = 100;
function pairSum(mat, n, sum) {
for (let i = 0; i < n; i++)
mat[i].sort((a, b) => a - b);
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
let left = 0, right = n - 1;
while (left < n && right >= 0) {
if ((mat[i][left] + mat[j][right]) == sum) {
document.write( "(" + mat[i][left] + ", " +
mat[j][right] + "), " );
left++;
right--;
}
else {
if ((mat[i][left] + mat[j][right]) < sum)
left++;
else
right--;
}
}
}
}
}
let n = 4, sum = 11;
let mat = [[1 , 3, 2, 4],
[5 , 8, 7, 6],
[9 , 10, 13, 11],
[12, 0, 14, 15]];
pairSum(mat, n, sum);
</script>
|
Output
(3, 8), (4, 7), (1, 10), (2, 9), (11, 0),
Time complexity : O(n2logn + n^3)
Auxiliary space : O(1)
Method 3 (Hashing)
- Create an empty hash table and store all elements of the matrix in the hash as keys and their locations as values.
- 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.
Implementation:
CPP
#include<bits/stdc++.h>
using namespace std;
const int MAX = 100;
void pairSum( int mat[][MAX], int n, int sum)
{
unordered_map< int , int > hm;
for ( int i=0; i<n; i++)
{
for ( int j=0; j<n; j++)
{
int remSum = sum - mat[i][j];
auto it = hm.find(remSum);
if (it != hm.end())
{
int row = hm[remSum];
if (row < i)
cout << "(" << mat[i][j] << ", "
<< remSum << "), " ;
}
hm[(mat[i][j])] = i;
}
}
}
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
import java.io.*;
import java.util.*;
class GFG
{
static int MAX = 100 ;
static void pairSum( int mat[][], int n, int sum)
{
Map<Integer,ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>();
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
{
hm.put(mat[i][j], new ArrayList<Integer>(Arrays.asList(i, j)) );
}
}
for ( int i = 0 ; i < n; i++)
{
for ( int j = 0 ; j < n; j++)
{
int remSum = sum - mat[i][j];
if (hm.containsKey(remSum))
{
ArrayList<Integer> p = hm.get(remSum);
int row = p.get( 0 ), col = p.get( 1 );
if (row != i && row > i)
{
System.out.print( "(" + mat[i][j] + "," + mat[row][col] + "), " );
}
}
}
}
}
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);
}
}
|
Python3
MAX = 100
def pairSum(mat, n, sum ):
hm = {}
for i in range (n):
for j in range (n):
hm[(mat[i][j])] = [i, j]
for i in range (n):
for j in range (n):
remSum = sum - mat[i][j]
if remSum in hm:
p = hm[remSum]
row = p[ 0 ]
col = p[ 1 ]
if (row ! = i and row > i):
print ( "(" , mat[i][j] , "," , mat[row][col] , "), " , end = "")
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 )
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static void pairSum( int [,] mat, int n, int sum)
{
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});
}
}
for ( int i = 0; i < n; i++)
{
for ( int j = 0; j < n; j++)
{
int remSum = sum - mat[i,j];
if (hm.ContainsKey(remSum))
{
List< int > p = hm[remSum];
int row = p[0], col = p[1];
if (row != i && row > i)
{
Console.Write( "(" + mat[i, j] + "," + mat[row, col] + "), " );
}
}
}
}
}
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);
}
}
|
Javascript
<script>
let MAX = 100;
function pairSum(mat,n,sum)
{
let hm = new Map();
for (let i = 0; i < n; i++)
{
for (let j = 0; j < n; j++)
{
hm.set(mat[i][j], [i, j] );
}
}
for (let i = 0; i < n; i++)
{
for (let j = 0; j < n; j++)
{
let remSum = sum - mat[i][j];
if (hm.has(remSum))
{
let p = hm.get(remSum);
let row = p[0], col = p[1];
if (row != i && row > i)
{
document.write( "(" + mat[i][j] + "," +
mat[row][col] + "), " );
}
}
}
}
}
let n = 4, sum = 11;
let mat = [[1, 3, 2, 4],
[5, 8, 7, 6],
[9, 10, 13, 11],
[12, 0, 14, 15]];
pairSum(mat, n, sum);
</script>
|
Output
(8, 3), (7, 4), (9, 2), (10, 1), (0, 11),
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.
Auxiliary Space: O(n2) because using HashMap
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...