![]() |
VOOZH | about |
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).
The Idea is go through every element in
mat1, and for each of those elements, check if the number needed to reachx(i.e.,x - elem) is present anywhere inmat2. If such a number is found, increase the count. In the end, return the total number of such matching pairs.
4
The idea is store all elements of
mat2[][]in a hash set for quick lookup. Then, for each elementeleinmat1[][], check if(x - ele)exists in the hash table. If it does, count it as a valid pair.
4
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:
Illustration:
4