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

PythonServer Side ProgrammingProgramming

Suppose we have a matrix of unique elements and a sum; we have to find all the pairs from the matrix whose sum is equal to given sum. Here, each element of pair will be taken from different rows.

So, if the input is like −

2435
6987
10111412
1311516

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

To solve this, we will follow these steps −

  • res := a new list

  • n := size of matrix

  • for i in range 0 to n, do

    • sort the list matrix[i]

  • for i in range 0 to n - 1, do

    • for j in range i + 1 to n, do

      • low := 0, high := n - 1

      • while low < n and high >= 0, do

        • if (matrix[i, low] + matrix[j, high]) is same as sum, then

          • pair := make pair using (matrix[i, low],matrix[j, high])

          • insert pair at the end of res

          • low := low + 1

          • high := high - 1

        • otherwise,

          • if (matrix[i][low] + matrix[j][high]) < sum, then

            • low := low + 1

          • otherwise,

            • high := high - 1

  • return res

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

MAX = 100
def sum_pair(matrix, sum):
   res = []
   n = len(matrix)
   for i in range(n):
   matrix[i].sort()
   for i in range(n - 1):
      for j in range(i + 1, n):
         low = 0
         high = n - 1
         while (low < n and high >= 0):
            if ((matrix[i][low] + matrix[j][high]) == sum):
               pair = (matrix[i][low],matrix[j][high])
               res.append(pair)
               low += 1
               high -= 1
         else:
         if ((matrix[i][low] + matrix[j][high]) < sum):
            low += 1
         else:
            high -= 1
   return res

sum = 13
matrix = [
   [2, 4, 3, 5],
   [6, 9, 8, 7],
   [10, 11, 14, 12],
   [13, 1, 15, 16]]
print(sum_pair(matrix, sum))

Input

[[2, 4, 3, 5],
[6, 9, 8, 7],
[10, 11, 14, 12],
[13, 1, 15, 16]]
sum = 13

Output

[(4, 9), (5, 8), (2, 11), (3, 10), (12, 1)]
raja
Published on 19-Aug-2020 10:59:08
Advertisements