01. Count pairs Sum in matrices
โ GFG solution for counting valid pairs from two matrices such that their sum equals X. Includes optimized two-pointer logic and more. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given two matrices mat1[][]
and mat2[][]
of size n x n
, where elements in each matrix are arranged in strictly ascending order (each row is sorted, and the last element of a row is smaller than the first element of the next row). You are given a target value x
. Count all pairs {a, b}
such that a
is from mat1
and b
is from mat2
, and a + b = x
.
๐ Examples
Example 1
Input:
n = 3, x = 21
mat1 = [
[1, 5, 6],
[8, 10, 11],
[15,16, 18]
]
mat2 = [
[2, 4, 7],
[9, 10, 12],
[13,16, 20]
]
Output: 4
Explanation:
Pairs summing to 21 are: (1,20), (5,16), (8,13), (11,10).
Example 2
Input:
n = 2, x = 10
mat1 = [
[1, 2],
[3, 4]
]
mat2 = [
[4, 5],
[6, 7]
]
Output: 2
Explanation:
Pairs summing to 10 are: (4,6), (3,7).
๐ Constraints
$1 \le n \le 100$
$1 \le \text{mat1}[i][j], ,\text{mat2}[i][j] \le 10^5$
$1 \le x \le 10^5$
Both matrices are sorted in row-major ascending order (strictly).
โ
My Approach: Two-Pointer Style Traversal (Optimized)
๐ก Idea:
We treat both matrices as flattened lists and scan from opposite ends โ start from top-left of a[][]
and bottom-right of b[][]
, moving in a two-pointer fashion based on the sum.
๐ง Algorithm Steps:
Initialize:
Pointer
r1 = 0, c1 = 0
for matrixa
Pointer
r2 = n-1, c2 = m-1
for matrixb
A
cnt
variable to store valid pair count.
While within bounds:
Compute
sum = a[r1][c1] + b[r2][c2]
If sum matches
x
, incrementcnt
, move both pointers.If sum < x, move
c1
forward ina
; if out-of-bounds, resetc1 = 0
, incrementr1
If sum > x, move
c2
backward inb
; if out-of-bounds, resetc2 = m-1
, decrementr2
Stop when either matrix is exhausted.
Return
cnt
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(nยฒ), because in the worst-case each of the
nยฒ
elements inmat1
andmat2
is visited once by the two pointers.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of extra space for pointers and counters.
๐งโ๐ป Code (C++)
class Solution {
public:
int countPairs(vector<vector<int>> &a, vector<vector<int>> &b, int x) {
int r1 = 0, c1 = 0, r2 = b.size() - 1, c2 = b[0].size() - 1, cnt = 0;
while (r1 < a.size() && r2 >= 0) {
int sum = a[r1][c1] + b[r2][c2];
if (sum == x) ++cnt, ++c1, --c2;
else if (sum < x) ++c1;
else --c2;
if (c1 == a[0].size()) c1 = 0, ++r1;
if (c2 < 0) c2 = b[0].size() - 1, --r2;
}
return cnt;
}
};
๐งโ๐ป Code (Java)
class Solution {
int countPairs(int[][] a, int[][] b, int x) {
int r1 = 0, c1 = 0, r2 = b.length - 1, c2 = b[0].length - 1, cnt = 0;
while (r1 < a.length && r2 >= 0) {
int sum = a[r1][c1] + b[r2][c2];
if (sum == x) { cnt++; c1++; c2--; }
else if (sum < x) c1++;
else c2--;
if (c1 == a[0].length) { c1 = 0; r1++; }
if (c2 < 0) { c2 = b[0].length - 1; r2--; }
}
return cnt;
}
}
๐ Code (Python)
class Solution:
def countPairs(self, a, b, x):
r1 = c1 = 0
r2, c2 = len(b) - 1, len(b[0]) - 1
cnt = 0
while r1 < len(a) and r2 >= 0:
s = a[r1][c1] + b[r2][c2]
if s == x:
cnt += 1
c1 += 1
c2 -= 1
elif s < x:
c1 += 1
else:
c2 -= 1
if c1 == len(a[0]):
c1 = 0
r1 += 1
if c2 < 0:
c2 = len(b[0]) - 1
r2 -= 1
return cnt
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated