Open In App

Find pairs with given sum such that elements of pair are in different rows

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Input : mat[][] = {{1, 5, 7},
{2, 6, 8},
{3, 4, 9}}
sum = 11
Output : (2, 9), (3, 8), (5, 6)

[Naive Approach] - Consider Every Element One by One - O(m2 x n2) Time and O(1) Space

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++
// C++ program to find a pair with given sum such that
// every element of pair is in different rows.
#include <bits/stdc++.h>
using namespace std;

// Function to find pair for given sum in matrix
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;
}

// Driver program to run the case
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;
}

// This code is contributed by hkdass001
Java
// Java program to find a pair with given sum such that
// every element of pair is in different rows.
import java.util.*;

public class GFG {

    // Function to find pair for given sum in matrix
    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;
    }

    // Driver program to run the case
    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);
    }
}

// This code is contributed by Karandeep1234
Python
# Function to find pair for given sum in matrix
def pair_sum(mat, target_sum):
    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] == target_sum:
                        print(f'({mat[i][k]}, {mat[j][l]}), ', end='')

# Driver program to run the case
sum_value = 11
mat = [[1, 3, 2, 4],
       [5, 8, 7, 6],
       [9, 10, 13, 11],
       [12, 0, 14, 15]]
pair_sum(mat, sum_value)

[Better Approach] - Sorting and Two Pointer - O(mn Log n + mn2) Time and O(1) Space

  • Sort all the rows in ascending order. The time complexity for this preprocessing will be O(m x n log n).
  • Now we 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 <bits/stdc++.h>
using namespace std;

// 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(vector<vector<int>>& mat, int sum)
{
    int n = mat.size();
  
    // First sort all the rows in ascending order
    for (int i=0; i<n; i++)
        sort(mat[i].begin(), mat[i].end());

    // 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 = mat[j].size()-1;
            while (left < mat[i].size() && 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--;
                }
            }
        }
    }
}

// Driver program to run the case
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
// Java program to find a pair with given sum such that
// every element of pair is in different rows.
import java.util.*;

public class PairSum {
  
    // Function to find pair for given sum in matrix
    // mat[][] --> given matrix
    // sum --> given sum for which we need to find pair
    static void pairSum(int[][] mat, int sum) {
        int n = mat.length;

        // 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 = mat[j].length - 1;
                while (left < mat[i].length && 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 program to run the case
    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);
    }
}
Python
# Function to find pair for given sum in matrix
# mat[][] --> given matrix
# sum --> given sum for which we need to find pair
def pair_sum(mat, sum):
    n = len(mat)
    
    # 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, right = 0, len(mat[j]) - 1
            while left < len(mat[i]) and right >= 0:
                if (mat[i][left] + mat[j][right]) == sum:
                    print(f'({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 program to run the case
sum_value = 11
mat = [[1, 3, 2, 4],
       [5, 8, 7, 6],
       [9, 10, 13, 11],
       [12, 0, 14, 15]]
pair_sum(mat, sum_value)
C#
// C# program to find a pair with given sum such that
// every element of pair is in different rows.
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    // Function to find pair for given sum in matrix
    // mat[][] --> given matrix
    // sum --> given sum for which we need to find pair
    static void PairSum(int[][] mat, int sum)
    {
        int n = mat.Length;

        // First sort all the rows in ascending order
        for (int i = 0; i < n; i++)
            Array.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 = mat[j].Length - 1;
                while (left < mat[i].Length && right >= 0)
                {
                    if ((mat[i][left] + mat[j][right]) == sum)
                    {
                        Console.WriteLine("(" + 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
    static void Main()
    {
        int sum = 11;
        int[][] mat = {
            new int[] {1, 3, 2, 4},
            new int[] {5, 8, 7, 6},
            new int[] {9, 10, 13, 11},
            new int[] {12, 0, 14, 15}
        };
        PairSum(mat, sum);
    }
}
JavaScript
// 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
function pairSum(mat, sum) {
    let n = mat.length;

    // First sort all the rows in ascending order
    for (let i = 0; i < n; i++)
        mat[i].sort((a, b) => a - b);

    // 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 (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            let left = 0, right = mat[j].length - 1;
            while (left < mat[i].length && right >= 0) {
                if ((mat[i][left] + mat[j][right]) === sum) {
                    console.log(`(${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
let sum = 11;
let mat = [[1, 3, 2, 4],
           [5, 8, 7, 6],
           [9, 10, 13, 11],
           [12, 0, 14, 15]];
pairSum(mat, sum);

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

[Expected Approach] - Hashing - O(mn) Time and O(mn) Space

  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.
C++
// C++ program to find pairs with given sum such
// the two elements of pairs are from different rows
#include <bits/stdc++.h>
using namespace std;

// Function to find pair for given sum in matrix
// mat[][] --> given matrix
// sum --> given sum for which we need to find pair
void pairSum(vector<vector<int>>& mat, int sum) {
  
    // Create a hash and store all elements of matrix
    // as keys, and row as values
    unordered_map<int, int> hm;

    // Get the order of the matrix
    int n = mat.size();

    // Traverse the matrix 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];
            auto it = hm.find(remSum); // it is an iterator
                                       // of unordered_map type

            // If an element with value equal to remaining sum exists
            if (it != hm.end()) {
              
                // Find row numbers of element with
                // value equal to remaining sum.
                int row = hm[remSum];

                // 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)
                   cout << "(" << mat[i][j] << ", " << remSum << "), ";
            }
            hm[mat[i][j]] = i;
        }
    }
}

// Driver program 
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
// Java program to find pairs with given sum such
// the two elements of pairs are from different rows
import java.util.HashMap;
import java.util.Map;

public class Main {
  
    // Function to find pair for given sum in matrix
    // mat[][] --> given matrix
    // sum --> given sum for which we need to find pair
    public static void pairSum(int[][] mat, int sum) {
      
        // Create a hash and store all elements of matrix
        // as keys, and row as values
        Map<Integer, Integer> hm = new HashMap<>();

        // Get the order of the matrix
        int n = mat.length;

        // Traverse the matrix 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 (hm.containsKey(remSum)) {
                  
                    // Find row numbers of element with
                    // value equal to remaining sum.
                    int row = hm.get(remSum);

                    // 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)
                        System.out.print("(" + mat[i][j] + ", " + remSum + "), ");
                }
                hm.put(mat[i][j], i);
            }
        }
    }

    // Driver program 
    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);
    }
}
Python
# Python program to find pairs with given sum such
# the two elements of pairs are from different rows

def pair_sum(mat, sum):
  
    # Create a hash and store all elements of matrix
    # as keys, and row as values
    hm = {}

    # Get the order of the matrix
    n = len(mat)

    # Traverse the matrix to check for every
    # element whether its pair exists or not.
    for i in range(n):
        for j in range(n):
          
            # Look for remaining sum in hash
            rem_sum = sum - mat[i][j]
            if rem_sum in hm:
              
                # Find row numbers of element with
                # value equal to remaining sum.
                row = hm[rem_sum]

                # 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:
                    print(f'({mat[i][j]}, {rem_sum}), ', end='')
            hm[mat[i][j]] = i

# Driver program 
if __name__ == '__main__':
    sum = 11
    mat = [[1, 3, 2, 4],
           [5, 8, 7, 6],
           [9, 10, 13, 11],
           [12, 0, 14, 15]]
    pair_sum(mat, sum)
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;

class Program {
  
    // Function to find pair for given sum in matrix
    // mat[][] --> given matrix
    // sum --> given sum for which we need to find pair
    public static void PairSum(int[][] mat, int sum) {
      
        // Create a hash and store all elements of matrix
        // as keys, and row as values
        Dictionary<int, int> hm = new Dictionary<int, int>();

        // Get the order of the matrix
        int n = mat.Length;

        // Traverse the matrix 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 (hm.ContainsKey(remSum)) {
                  
                    // Find row numbers of element with
                    // value equal to remaining sum.
                    int row = hm[remSum];

                    // 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)
                        Console.Write("(" + mat[i][j] + ", " + remSum + "), ");
                }
                hm[mat[i][j]] = i;
            }
        }
    }

    // Driver program 
    public static void Main() {
        int sum = 11;
        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}
        };
        PairSum(mat, sum);
    }
}
JavaScript
// Function to find pairs with given sum such that 
// the two elements of pairs are from different rows
function pairSum(mat, sum) {

    // Create a hash and store all elements of matrix 
    // as keys, and row as values
    let hm = {};

    // Get the order of the matrix
    let n = mat.length;

    // Traverse the matrix to check for every element
    // whether its pair exists or not.
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
        
            // Look for remaining sum in hash
            let remSum = sum - mat[i][j];
            if (remSum in hm) {
            
                // Find row numbers of element with value 
                // equal to remaining sum.
                let row = hm[remSum];

                // 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) {
                    console.log(`(${mat[i][j]}, ${remSum}), `);
                }
            }
            hm[mat[i][j]] = i;
        }
    }
}

// Driver program 
let sum = 11;
let mat = [[1, 3, 2, 4],
           [5, 8, 7, 6],
           [9, 10, 13, 11],
           [12, 0, 14, 15]];
pairSum(mat, sum);

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.


Next Article

Similar Reads