githubEdit

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 Linkarrow-up-right

๐Ÿงฉ 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

๐Ÿ”’ 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:

  1. Initialize:

    • Pointer r1 = 0, c1 = 0 for matrix a

    • Pointer r2 = n-1, c2 = m-1 for matrix b

    • A cnt variable to store valid pair count.

  2. While within bounds:

    • Compute sum = a[r1][c1] + b[r2][c2]

    • If sum matches x, increment cnt, move both pointers.

    • If sum < x, move c1 forward in a; if out-of-bounds, reset c1 = 0, increment r1

    • If sum > x, move c2 backward in b; if out-of-bounds, reset c2 = m-1, decrement r2

  3. Stop when either matrix is exhausted.

  4. Return cnt

๐Ÿ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(nยฒ), because in the worst-case each of the nยฒ elements in mat1 and mat2 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++)

chevron-rightโšก View Alternative Approaches with Code and Analysishashtag

๐Ÿ“Š 2๏ธโƒฃ Hash Map (Value Frequency Counter)

๐Ÿ’ก Algorithm Steps:

  1. Traverse all elements of mat2 and store their frequencies in a unordered_map<int, int>.

  2. Iterate over mat1 and for each element a[i][j], compute rem = x - a[i][j].

  3. Increment count by frequency of rem in the map.

๐Ÿ“ Complexity Analysis:

  • Time: โฑ๏ธ O(nยฒ)

  • Auxiliary Space: ๐Ÿ’พ O(nยฒ)

โœ… Why This Approach?

  • Efficient for unsorted matrices.

  • Leverages constant-time hashmap lookup.

๐Ÿ“Š 3๏ธโƒฃ Sort + Two Pointer on Flattened Grids

๐Ÿ’ก Algorithm Steps:

  1. Flatten both matrices into 1D arrays.

  2. Sort a_flat in ascending and b_flat in descending order.

  3. Use two pointers to count pairs summing to x.

๐Ÿ“ Complexity Analysis:

  • Time: โฑ๏ธ O(nยฒ log n)

  • Auxiliary Space: ๐Ÿ’พ O(nยฒ)

โœ… Why This Approach?

  • Good balance of time and space if flattening is viable.

  • Works when matrix values are disorganized.

๐Ÿ“Š 4๏ธโƒฃ Brute Force (Double Nested Loops)

๐Ÿ’ก Algorithm Steps:

  1. Use two nested loops to try every combination of elements from mat1 and mat2.

  2. Count all pairs whose sum equals x.

๐Ÿ“ Complexity Analysis:

  • Time: โฑ๏ธ O(nโด)

  • Auxiliary Space: ๐Ÿ’พ O(1)

โœ… Why This Approach?

  • Works universally without needing sorting or extra space.

  • Very inefficient for large matrices.

โš ๏ธ Warning: TLE on Large Inputs

โœ… Test Cases Passed: 1010 / 1115

โŒ Result: Time Limit Exceeded (TLE)

๐Ÿ•“ Issue: Brute-force algorithm exceeded time constraints on larger test cases due to O(nโด) complexity Wonโ€™t pass when n approaches 100 due to time explosion.

๐Ÿ†š ๐Ÿ” Comparison of Approaches

๐Ÿš€ Approach

โฑ๏ธ Time Complexity

๐Ÿ’พ Space Complexity

โœ… Pros

โš ๏ธ Cons

๐Ÿ” Two Pointer

๐ŸŸข O(nยฒ)

๐ŸŸข O(1)

Fast for sorted matrices

Needs sorted grid

๐Ÿ“ฆ Hash Map

๐ŸŸข O(nยฒ)

๐ŸŸก O(nยฒ)

Best for unsorted matrices

Extra memory

๐Ÿงฎ Sort + 2-Pointer

๐ŸŸก O(nยฒ log n)

๐ŸŸก O(nยฒ)

Efficient for disjoint matrices

Needs full flatten and sort

๐Ÿข Brute Force (TLE)

๐Ÿ”ด O(nโด)

๐ŸŸข O(1)

Simplest universal logic

Extremely slow for large inputs

๐Ÿ† Best Choice Recommendation

๐ŸŽฏ Scenario

๐Ÿฅ‡ Recommended Approach

โœ… Both matrices sorted

๐Ÿฅ‡ Two Pointer

๐Ÿ“‹ Matrices unsorted

๐Ÿฅˆ Hash Map

๐Ÿ’ฅ Arrays easily flattenable

๐Ÿฅ‰ Sort + Two Pointer

๐Ÿ” Small size or brute force benchmark

๐ŸŽ–๏ธ Brute Force (TLE)

๐Ÿง‘โ€๐Ÿ’ป Code (Java)

๐Ÿ Code (Python)

๐Ÿง  Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐Ÿ“ฌ Any Questions?arrow-up-right. Letโ€™s make this learning journey more collaborative!

โญ If you find this helpful, please give this repository a star! โญ


๐Ÿ“Visitor Count

Visitor counter

Last updated