Find the Pair with Given Sum in a Matrix using C++


In this article, we will discuss the program of finding a pair with a given sum in a given matrix. For example −

Input : matrix[n][m] = { 
   { 4, 6, 4, 65 }, 
   { 56, 1, 12, 32 },
   { 4, 5, 6, 44 },
   { 13, 9, 11, 25 } 
}, SUM = 20

Output : Pair exists.
Explanation : Sum = 20 is equal to the sum of numbers 9 and 11 which exists in the matrix.

Input : matrix[n][m] = { 
   { 5, 7, 3, 45 },  
   { 63, 5, 3, 7 },  
   { 11, 6, 9, 5 },
   { 8, 6, 14, 15 } 
}, SUM = 13
Output : Pair does not exist.
Explanation : No pair exists in the matrix whose sum is equal to 7.

Approach to find The Solution

Now we will explain two different approaches to find the solution of the above problem.

Brute-Force Approach

Considering each pair in the given matrix and checking whether the sum of the pair is equal to the given SUM, if yes, then print “Pair exists”; otherwise, print “Pair does not exist.” Applying this approach is very simple, but it will shoot up the time complexity to O((N*M)2).

Efficient Approach

This program can be efficient by using a hash to store all the matrix elements and then traverse through the matrix and check whether the difference of [ SUM & (index element) ] is equal. If YES, then Print “Exist” and exit the program. If NO, then after traversing print, “does not exist.”

Example

#include <bits/stdc++.h>
using namespace std;

#define n 4
#define m 4

int main() {
   int matrix[n][m] = { 
      { 5,7, 3,45 },
      { 63, 5, 3, 7 },
      { 11, 6, 9, 5 },
      { 8, 6, 14, 15 } 
   };

   int sum = 7;
   unordered_set<int> hash;

   for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
         if (hash.find(sum - matrix[i][j]) != hash.end()) {
            cout << "Pair exists." << endl;
            return 0;
         } else {
            hash.insert(matrix[i][j]);
         }
      }
   }

   cout << "Pair does not exist." << endl;
   return 0;
}

Output

Pair does not exist.

Explanation of the above code

  • Declaring 2-D array and storing elements in it.
  • Traversing through the array finding if (sum - matrix[i][j]) != hash.end().
  • If the condition satisfies, then print “Pair exists” and return from the main function.
  • Otherwise, keep traversing the array and finally print “ Pair does not exist.”

Conclusion

In this article, we discussed finding a pair with a given sum in a matrix or 2-D array; We discussed the Brute-force approach and an Efficient approach to solve this problem. We discussed the C++ program to solve this problem. However, we can write this program in any other language like C, Java, Python, etc. We hope you find this article helpful.

Updated on: 26-Nov-2021

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements