Open In App

Count pairs from two sorted matrices with given sum

Last Updated : 22 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
// C++ program to Count pairs from 
// two sorted matrices with given sum
#include <iostream>
#include <vector>
using namespace std;

// Function to search 'val' in mat
// Returns true if 'val' is present, else false
bool valuePresent(vector<vector<int>>& mat, int val) {
    for (auto& row : mat)
        for (int elem : row)
            if (elem == val)
                return true; 
    return false; 
}

// Function to count pairs from two sorted matrices
// whose sum is equal to a given value x
int countPairs(vector<vector<int>>& mat1, 
               vector<vector<int>>& mat2, int x) {
    int count = 0;

    for (auto& row : mat1)
        for (int elem : row)
          
            // Check if (x - elem) exists in mat2
            if (valuePresent(mat2, x - elem))
                count++;

    return count; 
}

int main() {
    vector<vector<int>> mat1 = {
        { 1, 5, 6 },
        { 8, 10, 11 },
        { 15, 16, 18 }
    };

    vector<vector<int>> mat2 = {
        { 2, 4, 7 },
        { 9, 10, 12 },
        { 13, 16, 20 }
    };

    int x = 21;

    cout << countPairs(mat1, mat2, x);

    return 0;
}
Java
// Java program to Count pairs from 
// two sorted matrices with given sum
import java.util.*;

class GfG {
    
    // Function to search 'val' in mat
    // Returns true if 'val' is present, else false
    static boolean valuePresent(int[][] mat, int val) {
        for (int[] row : mat)
            for (int elem : row)
                if (elem == val)
                    return true;
        return false;
    }

    // Function to count pairs from two sorted matrices
    // whose sum is equal to a given value x
    static int countPairs(int[][] mat1, int[][] mat2, int x) {
        int count = 0;

        for (int[] row : mat1)
            for (int elem : row)
                // Check if (x - elem) exists in mat2
                if (valuePresent(mat2, x - elem))
                    count++;

        return count;
    }

    public static void main(String[] args) {
        int[][] mat1 = {
            { 1, 5, 6 },
            { 8, 10, 11 },
            { 15, 16, 18 }
        };

        int[][] mat2 = {
            { 2, 4, 7 },
            { 9, 10, 12 },
            { 13, 16, 20 }
        };

        int x = 21;

        System.out.println(countPairs(mat1, mat2, x));
    }
}
Python
# Python program to Count pairs from 
# two sorted matrices with given sum

# Function to search 'val' in mat
# Returns true if 'val' is present, else false
def valuePresent(mat, val):
    for row in mat:
        for elem in row:
            if elem == val:
                return True
    return False

# Function to count pairs from two sorted matrices
# whose sum is equal to a given value x
def countPairs(mat1, mat2, x):
    count = 0

    for row in mat1:
        for elem in row:
            # Check if (x - elem) exists in mat2
            if valuePresent(mat2, x - elem):
                count += 1

    return count

if __name__ == "__main__":
    mat1 = [
        [1, 5, 6],
        [8, 10, 11],
        [15, 16, 18]
    ]

    mat2 = [
        [2, 4, 7],
        [9, 10, 12],
        [13, 16, 20]
    ]

    x = 21

    print(countPairs(mat1, mat2, x))
C#
// C# program to Count pairs from 
// two sorted matrices with given sum
using System;

class GfG {
    
    // Function to search 'val' in mat
    // Returns true if 'val' is present, else false
    static bool valuePresent(int[,] mat, int val) {
        for (int i = 0; i < mat.GetLength(0); i++)
            for (int j = 0; j < mat.GetLength(1); j++)
                if (mat[i,j] == val)
                    return true;
        return false;
    }

    // Function to count pairs from two sorted matrices
    // whose sum is equal to a given value x
    static int countPairs(int[,] mat1, int[,] mat2, int x) {
        int count = 0;

        for (int i = 0; i < mat1.GetLength(0); i++)
            for (int j = 0; j < mat1.GetLength(1); j++)
                // Check if (x - elem) exists in mat2
                if (valuePresent(mat2, x - mat1[i,j]))
                    count++;

        return count;
    }

    static void Main() {
        int[,] mat1 = {
            { 1, 5, 6 },
            { 8, 10, 11 },
            { 15, 16, 18 }
        };

        int[,] mat2 = {
            { 2, 4, 7 },
            { 9, 10, 12 },
            { 13, 16, 20 }
        };

        int x = 21;

        Console.WriteLine(countPairs(mat1, mat2, x));
    }
}
JavaScript
// JavaScript program to Count pairs from 
// two sorted matrices with given sum

// Function to search 'val' in mat
// Returns true if 'val' is present, else false
function valuePresent(mat, val) {
    for (let row of mat)
        for (let elem of row)
            if (elem === val)
                return true;
    return false;
}

// Function to count pairs from two sorted matrices
// whose sum is equal to a given value x
function countPairs(mat1, mat2, x) {
    let count = 0;

    for (let row of mat1)
        for (let elem of row)
            // Check if (x - elem) exists in mat2
            if (valuePresent(mat2, x - elem))
                count++;

    return count;
}

let mat1 = [
    [1, 5, 6],
    [8, 10, 11],
    [15, 16, 18]
];

let mat2 = [
    [2, 4, 7],
    [9, 10, 12],
    [13, 16, 20]
];

let x = 21;

console.log(countPairs(mat1, mat2, x));

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.

C++
// C++ program to Count pairs from 
// two sorted matrices with given sum
#include <bits/stdc++.h>
using namespace std;

// Function to count pairs from two sorted matrices
// whose sum is equal to a given value x
int countPairs(vector<vector<int>>& mat1, 
               vector<vector<int>>& mat2, int x) {
  
    // Insert all elements of mat2 into the set
    unordered_set<int> set;
    for (auto& row : mat2) {
        for (int elem : row) {
            set.insert(elem);
        }
    }

    // For each element of mat1, check if 
    // (x - element) is in the set
    int count = 0;
    for (auto& row : mat1) {
        for (int elem : row) {
            if (set.find(x - elem) != set.end()) {
                count++;
            }
        }
    }
    return count;
}

int main() {
    vector<vector<int>> mat1 = {
        { 1, 5, 6 },
        { 8, 10, 11 },
        { 15, 16, 18 }
    };

    vector<vector<int>> mat2 = {
        { 2, 4, 7 },
        { 9, 10, 12 },
        { 13, 16, 20 }
    };

    int x = 21;

    cout << countPairs(mat1, mat2, x);

    return 0;
}
Java
// Java program to Count pairs from 
// two sorted matrices with given sum
import java.util.HashSet;
import java.util.Set;

class GfG {
    
    // Function to count pairs from two sorted matrices
    // whose sum is equal to a given value x
    static int countPairs(int[][] mat1, int[][] mat2, int x) {
        
        // Insert all elements of mat2 into the set
        Set<Integer> set = new HashSet<>();
        for (int[] row : mat2) {
            for (int elem : row) {
                set.add(elem);
            }
        }

        // For each element of mat1, check if 
        // (x - element) is in the set
        int count = 0;
        for (int[] row : mat1) {
            for (int elem : row) {
                if (set.contains(x - elem)) {
                    count++;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[][] mat1 = {
            { 1, 5, 6 },
            { 8, 10, 11 },
            { 15, 16, 18 }
        };

        int[][] mat2 = {
            { 2, 4, 7 },
            { 9, 10, 12 },
            { 13, 16, 20 }
        };

        int x = 21;

        System.out.println(countPairs(mat1, mat2, x));
    }
}
Python
# Python program to Count pairs from 
# two sorted matrices with given sum

# Function to count pairs from two sorted matrices
# whose sum is equal to a given value x
def countPairs(mat1, mat2, x):
    
    # Insert all elements of mat2 into the set
    elements = set()
    for row in mat2:
        for elem in row:
            elements.add(elem)

    # For each element of mat1, check if 
    # (x - element) is in the set
    count = 0
    for row in mat1:
        for elem in row:
            if (x - elem) in elements:
                count += 1
    return count

if __name__ == "__main__":
    mat1 = [
        [1, 5, 6],
        [8, 10, 11],
        [15, 16, 18]
    ]

    mat2 = [
        [2, 4, 7],
        [9, 10, 12],
        [13, 16, 20]
    ]

    x = 21

    print(countPairs(mat1, mat2, x))
C#
// C# program to Count pairs from 
// two sorted matrices with given sum
using System;
using System.Collections.Generic;

class GfG {
    
    // Function to count pairs from two sorted matrices
    // whose sum is equal to a given value x
    static int countPairs(int[,] mat1, int[,] mat2, int x) {
        
        // Insert all elements of mat2 into the set
        HashSet<int> set = new HashSet<int>();
        for (int i = 0; i < mat2.GetLength(0); i++) {
            for (int j = 0; j < mat2.GetLength(1); j++) {
                set.Add(mat2[i,j]);
            }
        }

        // For each element of mat1, check if 
        // (x - element) is in the set
        int count = 0;
        for (int i = 0; i < mat1.GetLength(0); i++) {
            for (int j = 0; j < mat1.GetLength(1); j++) {
                if (set.Contains(x - mat1[i,j])) {
                    count++;
                }
            }
        }
        return count;
    }

    static void Main() {
        int[,] mat1 = {
            { 1, 5, 6 },
            { 8, 10, 11 },
            { 15, 16, 18 }
        };

        int[,] mat2 = {
            { 2, 4, 7 },
            { 9, 10, 12 },
            { 13, 16, 20 }
        };

        int x = 21;

        Console.WriteLine(countPairs(mat1, mat2, x));
    }
}
JavaScript
// JavaScript program to Count pairs from 
// two sorted matrices with given sum

// Function to count pairs from two sorted matrices
// whose sum is equal to a given value x
function countPairs(mat1, mat2, x) {
    
    // Insert all elements of mat2 into the set
    const set = new Set();
    for (const row of mat2) {
        for (const elem of row) {
            set.add(elem);
        }
    }

    // For each element of mat1, check if 
    // (x - element) is in the set
    let count = 0;
    for (const row of mat1) {
        for (const elem of row) {
            if (set.has(x - elem)) {
                count++;
            }
        }
    }
    return count;
}

const mat1 = [
    [1, 5, 6],
    [8, 10, 11],
    [15, 16, 18]
];

const mat2 = [
    [2, 4, 7],
    [9, 10, 12],
    [13, 16, 20]
];

const x = 21;

console.log(countPairs(mat1, mat2, x));

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:

C++
// C++ program to Count pairs from 
// two sorted matrices with given sum
#include <bits/stdc++.h>
using namespace std;

// Function to count pairs from two sorted matrices
// whose sum is equal to a given value x
int countPairs(vector<vector<int>>& mat1, 
               vector<vector<int>>& mat2, int x) {
    int n = mat1.size();
  
    // Indices for pointing current element in mat1 and mat2
    int i = 0, j = (n*n -1);

    int count = 0;

    // While there are elements in both matrices
    while (i < n*n && j >= 0) {
        int r1 = i/n, c1 = i%n;
        int r2 = j/n, c2 = j%n;
        int val = mat1[r1][c1] + mat2[r2][c2];

        if (val == x) {
            count++;

            // Move i and j
            i++;
            j--;
        } 
        else if (val < x) {
            i++;
        } 
        else {
            j--; 
        }
    }

    return count;
}

int main() {
    vector<vector<int>> mat1 = {
        { 1, 5, 6 },
        { 8, 10, 11 },
        { 15, 16, 18 }
    };

    vector<vector<int>> mat2 = {
        { 2, 4, 7 },
        { 9, 10, 12 },
        { 13, 16, 20 }
    };

    int x = 21;

    cout << countPairs(mat1, mat2, x);

    return 0;
}
Java
// Java program to Count pairs from 
// two sorted matrices with given sum
class GfG {
    
    // Function to count pairs from two sorted matrices
    // whose sum is equal to a given value x
    static int countPairs(int[][] mat1, int[][] mat2, int x) {
        int n = mat1.length;
  
        // Indices for pointing current element in mat1 and mat2
        int i = 0, j = (n*n -1);

        int count = 0;

        // While there are elements in both matrices
        while (i < n * n && j >= 0) {
            int r1 = i/n, c1 = i%n;
            int r2 = j/n, c2 = j%n;
            int val = mat1[r1][c1] + mat2[r2][c2];

            if (val == x) {
                count++;

                // Move i and j
                i++;
                j--;
            } 
            else if (val < x) {
                i++;
            } 
            else {
                j--; 
            }
        }

        return count;
    }

    public static void main(String[] args) {
        int[][] mat1 = {
            { 1, 5, 6 },
            { 8, 10, 11 },
            { 15, 16, 18 }
        };

        int[][] mat2 = {
            { 2, 4, 7 },
            { 9, 10, 12 },
            { 13, 16, 20 }
        };

        int x = 21;

        System.out.println(countPairs(mat1, mat2, x));
    }
}
Python
# Python program to Count pairs from 
# two sorted matrices with given sum

# Function to count pairs from two sorted matrices
# whose sum is equal to a given value x
def countPairs(mat1, mat2, x):
    n = len(mat1)
  
    # Indices for pointing current element in mat1 and mat2
    i, j = 0, (n*n -1)

    count = 0

    # While there are elements in both matrices
    while i < n*n and j >= 0:
        r1, c1 = i//n, i%n
        r2, c2 = j//n, j%n
        val = mat1[r1][c1] + mat2[r2][c2]

        if val == x:
            count += 1
            
            # Move i and j
            i += 1
            j -= 1
        elif val < x:
            i += 1
        else:
            j -= 1

    return count

if __name__ == "__main__":
    mat1 = [
        [1, 5, 6],
        [8, 10, 11],
        [15, 16, 18]
    ]

    mat2 = [
        [2, 4, 7],
        [9, 10, 12],
        [13, 16, 20]
    ]

    x = 21

    print(countPairs(mat1, mat2, x))
C#
// C# program to Count pairs from 
// two sorted matrices with given sum
using System;

class GfG {
    
    // Function to count pairs from two sorted matrices
    // whose sum is equal to a given value x
    static int countPairs(int[,] mat1, int[,] mat2, int x) {
        int n = mat1.GetLength(0);
  
        // Indices for pointing current element in mat1 and mat2
        int i = 0, j = (n*n -1);

        int count = 0;

        // While there are elements in both matrices
        while (i < n*n && j >= 0) {
            int r1 = i/n, c1 = i%n;
            int r2 = j/n, c2 = j%n;
            int val = mat1[r1,c1] + mat2[r2,c2];

            if (val == x) {
                count++;

                // Move i and j
                i++;
                j--;
            } 
            else if (val < x) {
                i++;
            } 
            else {
                j--; 
            }
        }

        return count;
    }

    static void Main() {
        int[,] mat1 = {
            { 1, 5, 6 },
            { 8, 10, 11 },
            { 15, 16, 18 }
        };

        int[,] mat2 = {
            { 2, 4, 7 },
            { 9, 10, 12 },
            { 13, 16, 20 }
        };

        int x = 21;

        Console.WriteLine(countPairs(mat1, mat2, x));
    }
}
JavaScript
// JavaScript program to Count pairs from 
// two sorted matrices with given sum

// Function to count pairs from two sorted matrices
// whose sum is equal to a given value x
function countPairs(mat1, mat2, x) {
    let n = mat1.length;
  
    // Indices for pointing current element in mat1 and mat2
    let i = 0, j = (n*n -1);

    let count = 0;

    // While there are elements in both matrices
    while (i < n*n && j >= 0) {
        let r1 = Math.floor(i/n), c1 = i%n;
        let r2 = Math.floor(j/n), c2 = j%n;
        let val = mat1[r1][c1] + mat2[r2][c2];

        if (val === x) {
            count++;

            // Move i and j
            i++;
            j--;
        } 
        else if (val < x) {
            i++;
        } 
        else {
            j--; 
        }
    }

    return count;
}

let mat1 = [
    [1, 5, 6],
    [8, 10, 11],
    [15, 16, 18]
];

let mat2 = [
    [2, 4, 7],
    [9, 10, 12],
    [13, 16, 20]
];

let x = 21;

console.log(countPairs(mat1, mat2, x));

Output
4

Next Article

Similar Reads