Find pairs with given sum such that elements of pair are in different rows in Python

Finding pairs with a given sum from different rows in a matrix is a common problem in data structures. We need to find all pairs where one element comes from one row and the other from a different row, and their sum equals the target value.

So, if the input matrix is ?

2 4 3 5
6 9 8 7
10 11 14 12
13 1 15 16

And sum = 13, then the output will be [(4, 9), (5, 8), (2, 11), (3, 10), (12, 1)]

Algorithm

The approach uses a two-pointer technique after sorting each row ?

  • Sort each row of the matrix

  • For each pair of rows (i, j) where i < j

  • Use two pointers: low at the start of row i, high at the end of row j

  • If sum equals target, add the pair and move both pointers

  • If sum is less than target, move low pointer right

  • If sum is greater than target, move high pointer left

Implementation

def sum_pair(matrix, target_sum):
    result = []
    n = len(matrix)
    
    # Sort each row for two-pointer technique
    for i in range(n):
        matrix[i].sort()
    
    # Check all pairs of rows
    for i in range(n - 1):
        for j in range(i + 1, n):
            low = 0
            high = n - 1
            
            # Two-pointer approach
            while low < n and high >= 0:
                current_sum = matrix[i][low] + matrix[j][high]
                
                if current_sum == target_sum:
                    pair = (matrix[i][low], matrix[j][high])
                    result.append(pair)
                    low += 1
                    high -= 1
                elif current_sum < target_sum:
                    low += 1
                else:
                    high -= 1
    
    return result

# Test the function
matrix = [
    [2, 4, 3, 5],
    [6, 9, 8, 7],
    [10, 11, 14, 12],
    [13, 1, 15, 16]
]
target_sum = 13

pairs = sum_pair(matrix, target_sum)
print("Pairs with sum", target_sum, ":", pairs)
Pairs with sum 13 : [(4, 9), (5, 8), (2, 11), (3, 10), (12, 1)]

How It Works

The algorithm works by sorting each row first, which enables the two-pointer technique. For each pair of rows, we start with the smallest element from the first row and the largest from the second row. Based on their sum compared to the target, we move the appropriate pointer ?

# Example walkthrough with rows [2,3,4,5] and [7,8,9,6] (after sorting: [6,7,8,9])
# Target sum = 13

row1 = [2, 3, 4, 5]  # already sorted
row2 = [6, 7, 8, 9]  # sorted version of [7,8,9,6]

print("Row 1:", row1)
print("Row 2:", row2)
print("Target sum:", 13)
print()

# Simulate two-pointer technique
low, high = 0, 3
while low < 4 and high >= 0:
    current_sum = row1[low] + row2[high]
    print(f"Checking: {row1[low]} + {row2[high]} = {current_sum}")
    
    if current_sum == 13:
        print(f"Found pair: ({row1[low]}, {row2[high]})")
        low += 1
        high -= 1
    elif current_sum < 13:
        print("Sum too small, move low pointer right")
        low += 1
    else:
        print("Sum too large, move high pointer left")
        high -= 1
    print()
Row 1: [2, 3, 4, 5]
Row 2: [6, 7, 8, 9]
Target sum: 13

Checking: 2 + 9 = 11
Sum too small, move low pointer right

Checking: 3 + 9 = 12
Sum too small, move low pointer right

Checking: 4 + 9 = 13
Found pair: (4, 9)

Checking: 5 + 8 = 13
Found pair: (5, 8)

Time Complexity

The time complexity is O(n³) where n is the number of rows/columns, as we check all pairs of rows and use two pointers for each pair. The space complexity is O(1) excluding the output list.

Conclusion

This approach efficiently finds all pairs with a given sum from different rows using the two-pointer technique. Sorting each row first enables the linear search within each row pair, making it optimal for this constraint.

Updated on: 2026-03-25T09:22:09+05:30

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements