Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Find Pairs with Given Sum in Different Rows in Python



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 −

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

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)]
Updated on: 2020-08-19T11:00:13+05:30

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements