VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-two-sorted-matrices-given-sum/

⇱ Count pairs from two sorted matrices with given sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count pairs from two sorted matrices with given sum

Last Updated : 22 May, 2025

Given two sorted matrices mat1 and mat2 of size n x n of distinct elements. Given a value x, the task is to count all pairs from both matrices whose sum is equal to x

Note: The pair has an element from each matrix. Matrices are strictly sorted which means that matrices are sorted in a way such that all elements in a row are sorted in increasing order and for row ā€˜i’, where 1 <= i <= n-1, first element of row 'i' is greater than the last element of row 'i-1'.

Example:

Input : mat1[][] = [[1, 5, 6],
[8, 10, 11],
[15, 16, 18]]

mat2[][] = [[2, 4, 7],
[9, 10, 12],
[13, 16, 20]]
x = 21
Output : 4
The pairs are: (1, 20), (5, 16), (8, 13) and (11, 10).

[Naive Approach] Using Nested Approach - O(n^4) Time and O(1) Space

The Idea is go through every element in mat1, and for each of those elements, check if the number needed to reach x (i.e., x - elem) is present anywhere in mat2. If such a number is found, increase the count. In the end, return the total number of such matching pairs.


Output
4

[Better Approach] Using Hash Set - O(n^2) Time and O(n^2) Space

The idea is store all elements of mat2[][] in a hash set for quick lookup. Then, for each element ele in mat1[][], check if (x - ele) exists in the hash table. If it does, count it as a valid pair.


Output
4

[Expected Approach] Using Two Pointers - O(n2) Time and O(1) Space

The idea is to use a two-pointer approach where we traverse the first matrix in ascending order and the second matrix in descending order. We start with a pointer at the beginning of the first matrix (smallest element) and another pointer at the end of the second matrix (largest element). Based on their sum compared to the target value x, we move the pointers accordingly until we've examined all possible pairs.

Step by step approach:

  1. Start with two pointers - one at the beginning of first matrix and one at the end of second matrix
  2. Calculate sum of elements at current pointers and compare with target value
  3. If sum equals target, increment count, move first pointer forward and second pointer backward
  4. If sum is less than target, move first pointer forward to get a larger sum
  5. If sum is greater than target, move second pointer backward to get a smaller sum

Illustration:


Output
4
Comment