The Wayback Machine - https://web.archive.org/web/20241108100348/https://www.geeksforgeeks.org/find-pairs-given-sum-elements-pair-different-rows/
Open In App

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

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a matrix of distinct values and a sum. The task is to find all the pairs in a given matrix whose summation is equal to the given sum. Each element of a pair must be from different rows i.e; the pair must not lie in the same row.

Examples:  

Input : mat[4][4] = {{1, 3, 2, 4},
                     {5, 8, 7, 6},
                     {9, 10, 13, 11},
                     {12, 0, 14, 15}}
        sum = 11
Output: (1, 10), (3, 8), (2, 9), (4, 7), (11, 0) 

Method 1 (Simple):

A simple solution for this problem is to, one by one, take each element of all rows and find pairs starting from the next immediate row in the matrix.

C++




// C++ program to find a pair with given sum such that
// every element of pair is in different rows.
#include <bits/stdc++.h>
using namespace std;
  
// Function to find pair for given sum in matrix
int pairSum(vector<vector<int> >& mat, int sum)
{
    int m = mat.size();
    int n = mat[0].size();
  
    int count = 0;
  
    for (int i = 0; i < m; i++) {
        for (int j = i + 1; j < m; j++) {
            for (int k = 0; k < n; k++) {
                for (int l = 0; l < n; l++) {
                    if (mat[i][k] + mat[j][l] == sum) {
                        cout << "(" << mat[i][k] << ", "
                             << mat[j][l] << "), ";
                    }
                }
            }
        }
    }
  
    return count;
}
  
// Driver program to run the case
int main()
{
    int sum = 11;
    vector<vector<int> > mat = { { 1, 3, 2, 4 },
                                 { 5, 8, 7, 6 },
                                 { 9, 10, 13, 11 },
                                 { 12, 0, 14, 15 } };
    pairSum(mat, sum);
    return 0;
}
  
// This code is contributed by hkdass001


Java




// Java program to find a pair with given sum such that
// every element of pair is in different rows.
import java.util.*;
  
public class GFG {
  
    // Function to find pair for given sum in matrix
    static int pairSum(int[][] mat, int sum)
    {
        int m = mat.length;
        int n = mat[0].length;
  
        int count = 0;
  
        for (int i = 0; i < m; i++) {
            for (int j = i + 1; j < m; j++) {
                for (int k = 0; k < n; k++) {
                    for (int l = 0; l < n; l++) {
                        if (mat[i][k] + mat[j][l] == sum) {
                            System.out.print(
                                "(" + mat[i][k] + ", "
                                + mat[j][l] + "), ");
                        }
                    }
                }
            }
        }
  
        return count;
    }
  
    // Driver program to run the case
    public static void main(String[] args)
    {
        int sum = 11;
        int[][] mat = { { 1, 3, 2, 4 },
                        { 5, 8, 7, 6 },
                        { 9, 10, 13, 11 },
                        { 12, 0, 14, 15 } };
        pairSum(mat, sum);
    }
}
  
// This code is contributed by Karandeep1234


Python3




# Python program to find a pair with given sum such that
# every element of pair is in different rows.
  
# Function to find pair for given sum in matrix
def pair_sum(mat, sum):
    count = 0
    m = len(mat)
    n = len(mat[0])
    for i in range(m):
        for j in range(i + 1, m):
            for k in range(n):
                for l in range(n):
                    if mat[i][k] + mat[j][l] == sum:
                        print(f"({mat[i][k]}, {mat[j][l]}), ")
    return count
  
sum = 11
mat = [[1, 3, 2, 4],
       [5, 8, 7, 6],
       [9, 10, 13, 11],
       [12, 0, 14, 15]]
pair_sum(mat, sum)
  
# This code is contributed by vikramshrisath177.


C#




// C# program to find a pair with given sum such that
// every element of pair is in different rows.
using System;
using System.Linq;
  
class Program
{
  static void Main(string[] args)
  {
    int[][] mat = new int[][] {
      new int[] { 1, 3, 2, 4 },
      new int[] { 5, 8, 7, 6 },
      new int[] { 9, 10, 13, 11 },
      new int[] { 12, 0, 14, 15 }
    };
  
    int sum = 11;
  
    int count = 0;
    for (int i = 0; i < mat.Length; i++)
    {
      for (int j = i + 1; j < mat.Length; j++)
      {
        for (int k = 0; k < mat[i].Length; k++)
        {
          for (int l = 0; l < mat[j].Length; l++)
          {
            if (mat[i][k] + mat[j][l] == sum)
            {
              Console.WriteLine("(" + mat[i][k] + ", " + mat[j][l] + ")");
              count++;
            }
          }
        }
      }
    }
  }
}
  
// This code is cotriuted by shivamsharma215


Javascript




<script>
  
// JavaScript program to find a pair with given sum such that
// every element of pair is in different rows.
  
// Function to find pair for given sum in matrix
function pairSum(mat, sum){
    m = mat.length;
    n = mat[0].length;
  
    count = 0;
  
    for (let i = 0; i < m; i++) {
        for (let j = i + 1; j < m; j++) {
            for (let k = 0; k < n; k++) {
                for (let l = 0; l < n; l++) {
                    if (mat[i][k] + mat[j][l] == sum) {
                        document.write("(", mat[i][k], ", ", mat[j][l], "), ");
                    }
                }
            }
        }
    }
  
    return count;
}
  
// Driver program to run the case
let sum = 11;
let mat = [[ 1, 3, 2, 4 ],
           [5, 8, 7, 6  ],
           [ 9, 10, 13, 11 ],
            [12, 0, 14, 15 ]];
pairSum(mat, sum);
  
</script>


Output

(3, 8), (4, 7), (1, 10), (2, 9), (11, 0), 

Time Complexity: O(m2*n2), where m and n are the numbers of rows and columns of the given matrix respectively.
Auxiliary Space: O(1)

Method 2 (Use Sorting)

  • Sort all the rows in ascending order. The time complexity for this preprocessing will be O(n2 logn).
  • Now we will select each row one by one and find pair elements in the remaining rows after the current row.
  • Take two iterators, left and right. left iterator points left corner of the current i’th row and right iterator points right corner of the next j’th row in which we are going to find a pair of elements.
  • If mat[i][left] + mat[j][right] < sum then left++ i.e; move in i’th row towards the right corner, otherwise right++ i.e; move in j’th row towards the left corner

Implementation:

C++




// C++ program to find a pair with given sum such that
// every element of pair is in different rows.
#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Function to find pair for given sum in matrix
// mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
void pairSum(int mat[][MAX], int n, int sum)
{
    // First sort all the rows in ascending order
    for (int i=0; i<n; i++)
        sort(mat[i], mat[i]+n);
  
    // Select i'th row and find pair for element in i'th
    // row in j'th row whose summation is equal to given sum
    for (int i=0; i<n-1; i++)
    {
        for (int j=i+1; j<n; j++)
        {
            int left = 0, right = n-1;
            while (left<n && right>=0)
            {
                if ((mat[i][left] + mat[j][right]) == sum)
                {
                    cout << "(" << mat[i][left]
                         << ", "<< mat[j][right] << "), ";
                    left++;
                    right--;
                }
                else
                {
                    if ((mat[i][left] + mat[j][right]) < sum)
                        left++;
                    else
                        right--;
                }
            }
        }
    }
}
  
// Driver program to run the case
int main()
{
    int n = 4, sum = 11;
    int mat[][MAX] = {{1, 3, 2, 4},
                      {5, 8, 7, 6},
                      {9, 10, 13, 11},
                      {12, 0, 14, 15}};
    pairSum(mat, n, sum);
    return 0;
}


Java




// Java program to find a pair with
// given sum such that every element
// of pair is in different rows.
import java.util.Arrays;
class GFG {
static final int MAX = 100;
  
// Function to find pair for given sum in
// matrix mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
static void pairSum(int mat[][], int n, int sum) {
      
    // First sort all the rows in ascending order
    for (int i = 0; i < n; i++)
    Arrays.sort(mat[i]);
  
    // Select i'th row and find pair for element in i'th
    // row in j'th row whose summation is equal to given sum
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int left = 0, right = n - 1;
            while (left < n && right >= 0) {
                if ((mat[i][left] + mat[j][right]) == sum) {
                System.out.print("(" + mat[i][left] + ", " +
                                     mat[j][right] + "), ");
                left++;
                right--;
                }
                else {
                    if ((mat[i][left] + mat[j][right]) < sum)
                        left++;
                    else
                        right--;
                }
            }
        }
    }
}
  
// Driver code
public static void main(String[] args) {
    int n = 4, sum = 11;
    int mat[]
        [] = {{1 ,  3,  2,  4},
              {5 ,  8,  7,  6},
              {9 , 10, 13, 11},
              {12,  0, 14, 15}};
    pairSum(mat, n, sum);
}
}
// This code is contributed by Anant Agarwal.


Python 3




# Python 3 program to find a pair with 
# given sum such that every element of 
# pair is in different rows.
MAX = 100
  
# Function to find pair for given 
# sum in matrix mat[][] --> given matrix
# n --> order of matrix
# sum --> given sum for which we 
# need to find pair
def pairSum(mat, n, sum):
  
    # First sort all the rows 
    # in ascending order
    for i in range(n):
        mat[i].sort()
  
    # Select i'th row and find pair for 
    # element in i'th row in j'th row
    # whose summation is equal to given sum
    for i in range(n - 1):
        for j in range(i + 1, n):
            left = 0
            right = n - 1
            while (left < n and right >= 0):
                if ((mat[i][left] + mat[j][right]) == sum):
                    print( "(", mat[i][left], 
                           ", ", mat[j][right], "), ", 
                                            end = " ")
                    left += 1
                    right -= 1
                  
                else:
                    if ((mat[i][left] + 
                         mat[j][right]) < sum):
                        left += 1
                    else:
                        right -= 1
  
# Driver Code
if __name__ == "__main__":
    n = 4
    sum = 11
    mat = [[1, 3, 2, 4],
           [5, 8, 7, 6],
           [9, 10, 13, 11],
           [12, 0, 14, 15]]
    pairSum(mat, n, sum)
  
# This code is contributed 
# by ChitraNayal


C#




// C# program to find a pair with
// given sum such that every element
// of pair is in different rows.
using System;
using System.Collections.Generic;
  
public class GFG {
  
// Function to find pair for given sum in
// matrix mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
static void pairSum(int [,]mat, int n, int sum) {
      
    // First sort all the rows in ascending order
    for (int i = 0; i < n; i++)
    {
        List<int> l = new List<int>();
        for(int j = 0; j<n;j++)
        {
            l.Add(mat[i,j]);
        }
        l.Sort();
          
        for(int j = 0; j<n;j++)
        {
            mat[i,j] = l[j];
        }
    }
  
    // Select i'th row and find pair for element in i'th
    // row in j'th row whose summation is equal to given sum
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int left = 0, right = n - 1;
            while (left < n && right >= 0) {
                if ((mat[i,left] + mat[j,right]) == sum) {
                Console.Write("(" + mat[i,left] + ", " +
                                     mat[j,right] + "), ");
                left++;
                right--;
                }
                else {
                    if ((mat[i,left] + mat[j,right]) < sum)
                        left++;
                    else
                        right--;
                }
            }
        }
    }
}
  
// Driver code
public static void Main(string[] args) {
    int n = 4, sum = 11;
    int [,]mat = {{1 ,  3,  2,  4},
              {5 ,  8,  7,  6},
              {9 , 10, 13, 11},
              {12,  0, 14, 15}};
    pairSum(mat, n, sum);
}
}
  
// This code is contributed by rutvik_56.


Javascript




<script>
  
// Javascript program to find a pair with
// given sum such that every element
// of pair is in different rows.
  
let MAX = 100;
   
// Function to find pair for given sum in
// matrix mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
function pairSum(mat, n, sum) {
       
    // First sort all the rows in ascending order
    for (let i = 0; i < n; i++)
        mat[i].sort((a, b) => a - b);
   
    // Select i'th row and find pair for element in i'th
    // row in j'th row whose summation is equal to given sum
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            let left = 0, right = n - 1;
            while (left < n && right >= 0) {
                if ((mat[i][left] + mat[j][right]) == sum) {
                    document.write("(" + mat[i][left] + ", " +
                                     mat[j][right] + "), ");
                    left++;
                        right--;
                }
                else {
                    if ((mat[i][left] + mat[j][right]) < sum)
                        left++;
                    else
                        right--;
                }
            }
        }
    }
}
  
// Driver program 
  
    let n = 4, sum = 11;
    let mat = [[1 ,  3,  2,  4],
              [5 ,  8,  7,  6],
              [9 , 10, 13, 11],
              [12,  0, 14, 15]];
                
    pairSum(mat, n, sum);
    
</script>


Output

(3, 8), (4, 7), (1, 10), (2, 9), (11, 0), 

Time complexity : O(n2logn + n^3) 
Auxiliary space : O(1)

Method 3 (Hashing)  

  1. Create an empty hash table and store all elements of the matrix in the hash as keys and their locations as values.
  2. Traverse the matrix again to check for every element whether its pair exists in the hash table or not. If it exists, then compare row numbers. If row numbers are not the same, then print the pair.

Implementation:

CPP




// C++ program to find pairs with given sum such
// the two elements of pairs are from different rows
#include<bits/stdc++.h>
using namespace std;
  
const int MAX = 100;
  
// Function to find pair for given sum in matrix
// mat[][] --> given matrix
// n --> order of matrix
// sum --> given sum for which we need to find pair
void pairSum(int mat[][MAX], int n, int sum)
{
    // Create a hash and store all elements of matrix
    // as keys, and row as values
    unordered_map<int, int> hm;
  
    // Traverse the matrix to check for every
    // element whether its pair exists or not.
    for (int i=0; i<n; i++)
    {
        for (int j=0; j<n; j++)
        {
            // Look for remaining sum in hash
            int remSum = sum - mat[i][j];
            auto it = hm.find(remSum); // it is an iterator
                                       // of unordered_map type
  
            // If an element with value equal to remaining sum exists
            if (it != hm.end())
            {
                // Find row numbers of element with
                // value equal to remaining sum.
                int row = hm[remSum];
  
                // If row number of pair is not same as current
                // row, then print it as part of result.
                // Second condition is there to make sure that a 
                // pair is printed only once.  
                if (row < i)
                   cout << "(" << mat[i][j] << ", "
                        << remSum << "), ";
            }
              hm[(mat[i][j])] = i;
        }
    }
}
  
// Driver program 
int main()
{
    int n = 4, sum = 11;
    int mat[][MAX]= {{1, 3, 2, 4},
                     {5, 8, 7, 6},
                     {9, 10, 13, 11},
                     {12, 0, 14, 15}};
    pairSum(mat, n, sum);
    return 0;
}


Java




// Java program to find pairs with given sum such 
// the two elements of pairs are from different rows 
import java.io.*;
import java.util.*;
class GFG
{
  
  static int MAX = 100; 
  
  // Function to find pair for given sum in matrix 
  // mat[][] --> given matrix 
  // n --> order of matrix 
  // sum --> given sum for which we need to find pair
  static void pairSum(int mat[][], int n, int sum) 
  {
  
    // Create a hash and store all elements of matrix 
    // as keys, and row and column numbers as values 
    Map<Integer,ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>();
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < n; j++)
      {
        hm.put(mat[i][j], new ArrayList<Integer>(Arrays.asList(i, j)) );
      }
  
    }
  
    // Traverse the matrix again to check for every 
    // element whether its pair exists or not. 
    for (int i = 0; i < n; i++) 
    {
      for (int j = 0; j < n; j++)
      {
  
        // Look for remaining sum in hash 
        int remSum = sum - mat[i][j]; 
  
        // If an element with value equal to remaining sum exists
        if(hm.containsKey(remSum))
        {
  
          // Find row and column numbers of element with 
          // value equal to remaining sum.
          ArrayList<Integer> p = hm.get(remSum);
          int row = p.get(0), col = p.get(1);
  
          // If row number of pair is not same as current 
          // row, then print it as part of result. 
          // Second condition is there to make sure that a  
          // pair is printed only once.   
          if (row != i && row > i) 
          {
            System.out.print("(" + mat[i][j] + "," + mat[row][col] + "), ");
          }
        }
      }
    }
  }
  
  // Driver code
  public static void main (String[] args) {
    int n = 4, sum = 11; 
    int[][] mat = {{1, 3, 2, 4}, 
                   {5, 8, 7, 6}, 
                   {9, 10, 13, 11}, 
                   {12, 0, 14, 15}}; 
    pairSum(mat, n, sum);
  }
}
  
// This code is contributed by avanitrachhadiya2155


Python3




# Python3 program to find pairs with given sum such
# the two elements of pairs are from different rows
MAX = 100
  
# Function to find pair for given sum in matrix
  # mat[][] --> given matrix
  # n --> order of matrix
  # sum --> given sum for which we need to find pair
def pairSum(mat, n, sum):
      
    # Create a hash and store all elements of matrix
    # as keys, and row and column numbers as values
    hm = {}
      
    for i in range(n):
        for j in range(n):
            hm[(mat[i][j])] = [i, j]
      
    # Traverse the matrix again to check for every
    # element whether its pair exists or not.
    for i in range(n):
        for j in range(n):
            
            # Look for remaining sum in hash
            remSum = sum - mat[i][j]
              
            # If an element with value equal to remaining sum exists
            if remSum in hm:
                
                # Find row and column numbers of element with
                # value equal to remaining sum.
                p=hm[remSum]
                row = p[0]
                col = p[1]
                  
                # If row number of pair is not same as current
                # row, then print it as part of result.
                # Second condition is there to make sure that a
                # pair is printed only once. 
                if (row != i and row > i):
                    print("(" , mat[i][j] , "," , mat[row][col] , "), ", end="")
                      
# Driver code
n = 4
sum = 11
mat = [[1, 3, 2, 4],
                   [5, 8, 7, 6],
                   [9, 10, 13, 11],
                   [12, 0, 14, 15]]
pairSum(mat, n, sum)
  
# This code is contributed by patel2127


C#




// C# program to find pairs with given sum such 
// the two elements of pairs are from different rows 
using System;
using System.Collections.Generic;
public class GFG
{    
  
  // Function to find pair for given sum in matrix 
  // mat[][] --> given matrix 
  // n --> order of matrix 
  // sum --> given sum for which we need to find pair
  static void pairSum(int[,] mat, int n, int sum) 
  {
  
    // Create a hash and store all elements of matrix 
    // as keys, and row and column numbers as values 
    Dictionary<int,List<int>> hm = new Dictionary<int,List<int>>();
    for (int i = 0; i < n; i++)
    {
      for (int j = 0; j < n; j++)
      {
        hm.Add(mat[i,j],new List<int>(){i,j});
      }
    }
  
    // Traverse the matrix again to check for every 
    // element whether its pair exists or not. 
    for (int i = 0; i < n; i++) 
    {
      for (int j = 0; j < n; j++)
      {
  
        // Look for remaining sum in hash 
        int remSum = sum - mat[i,j]; 
  
        // If an element with value equal to remaining sum exists
        if(hm.ContainsKey(remSum))
        {
  
          // Find row and column numbers of element with 
          // value equal to remaining sum.
          List<int> p = hm[remSum];
          int row = p[0], col = p[1];
  
          // If row number of pair is not same as current 
          // row, then print it as part of result. 
          // Second condition is there to make sure that a  
          // pair is printed only once.   
          if (row != i && row > i) 
          {
            Console.Write("(" + mat[i, j] + "," + mat[row, col] + "), ");
          }
        }
      }
    }
  }
  
  // Driver code
  static public void Main (){
    int n = 4, sum = 11; 
    int[,] mat = {{1, 3, 2, 4}, 
                  {5, 8, 7, 6}, 
                  {9, 10, 13, 11}, 
                  {12, 0, 14, 15}}; 
    pairSum(mat, n, sum);
  }
}
  
// This code is contributed by rag2127


Javascript




<script>
  
// JavaScript program to find pairs with given sum such
// the two elements of pairs are from different rows
  
let MAX = 100;
  
// Function to find pair for given sum in matrix
  // mat[][] --> given matrix
  // n --> order of matrix
  // sum --> given sum for which we need to find pair
function pairSum(mat,n,sum)
{
    // Create a hash and store all elements of matrix
    // as keys, and row and column numbers as values
    let hm = new Map();
    for (let i = 0; i < n; i++)
    {
      for (let j = 0; j < n; j++)
      {
        hm.set(mat[i][j], [i, j] );
      }
   
    }
   
    // Traverse the matrix again to check for every
    // element whether its pair exists or not.
    for (let i = 0; i < n; i++)
    {
      for (let j = 0; j < n; j++)
      {
   
        // Look for remaining sum in hash
        let remSum = sum - mat[i][j];
   
        // If an element with value equal to remaining sum exists
        if(hm.has(remSum))
        {
   
          // Find row and column numbers of element with
          // value equal to remaining sum.
          let p = hm.get(remSum);
          let row = p[0], col = p[1];
   
          // If row number of pair is not same as current
          // row, then print it as part of result.
          // Second condition is there to make sure that a 
          // pair is printed only once.  
          if (row != i && row > i)
          {
            document.write("(" + mat[i][j] + "," +
            mat[row][col] + "), ");
          }
        }
      }
    }
}
  
// Driver code
let n = 4, sum = 11;
let mat = [[1, 3, 2, 4],
                   [5, 8, 7, 6],
                   [9, 10, 13, 11],
                   [12, 0, 14, 15]];
    pairSum(mat, n, sum);
  
  
  
// This code is contributed by ab2127
  
</script>


Output

(8, 3), (7, 4), (9, 2), (10, 1), (0, 11), 

One important thing is, when we traverse a matrix, a pair may be printed twice. To make sure that a pair is printed only once, we check if the row number of other elements picked from the hash table is more than the row number of the current element.

Time Complexity: O(n2) under the assumption that hash table inserts and search operations take O(1) time.
Auxiliary Space: O(n2) because using HashMap



Previous Article
Next Article

Similar Reads

Find pairs with given sum such that pair elements lie in different BSTs
Given two Binary Search Trees (BST) and a given sum. The task is to find pairs with given sum such that each pair elements must lie in different BST. Examples: Input : sum = 10 8 5 / \ / \ 3 10 2 18 / \ \ / \ 1 6 14 1 3 / \ / \ 5 7 13 4 Output : (5,5), (6,4), (7,3), (8,2) In above pairs first element lies in first BST and second element lies in sec
14 min read
Find N - 1 pairs from given array such that GCD of all pair-sums is greater than 1
Given an array arr[] of 2 * N integers, the task is to find a set of N - 1 pairs such that the GCD of all pair sums is greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}Output:1 32 4Explanation: The given array has 3 * 2 elements. The pair (1, 3) and (2, 4) has sum of elements as 4 and 6 respectively. Also, GCD(4, 6) > 1. Hence, (1, 3)
7 min read
Pair formation such that maximum pair sum is minimized
Given an array of size 2 * N integers. Divide the array into N pairs, such that the maximum pair sum is minimized. In other words, the optimal division of array into N pairs should result into a maximum pair sum which is minimum of other maximum pair sum of all possibilities. Examples: Input : N = 2 , arr[] = { 5, 8, 3, 9 } Output : (3, 9) (5, 8) E
5 min read
Number of indices pair such that element pair sum from first Array is greater than second Array
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] > B[i] + B[j] and i < j.Examples: Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indices {i, j} in the array following the condition. The
15+ min read
Find N-1 pairs (X, Y) from given array such that X and Y are different and X modulo Y is not present in array
Given an array Arr[] of size N consisting of N pairwise distinct positive integers. The task is to find N - 1 different pair of positive integers X, Y that satisfy the following conditions : X ≠ YX, Y both belong to the array.X mod Y does not belong to the array. Note: It is proved that N-1 such pairs always exists. Examples: Input: N = 4 , Arr [ ]
5 min read
Check if an array of pairs can be sorted by swapping pairs with different first elements
Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {{340000, 2}, {45000, 1}, {30000
11 min read
Count ordered pairs of Array elements such that bitwise AND of K and XOR of the pair is 0
Given an array arr[] of size N and an integer K, the task is to find the count of all the ordered pairs (i, j) where i != j, such that ((arr[i] ⊕ arr[j]) & K) = 0. The ⊕ represents bitwise XOR and & represents bitwise AND. Examples: Input: arr = [1, 2, 3, 4, 5], K = 3Output: 2Explanation: There are 2 pairs satisfying the condition. These pa
4 min read
Minimum pairs required to be removed such that the array does not contain any pair with sum K
Given an array arr[] of size N and an integer K, the task is to find the minimum count of pairs required to be removed such that no pair exists in the array whose sum of elements is equal to K. Examples: Input: arr[] = { 3, 1, 3, 4, 3 }, K = 6 Output: 1 Explanation: Removing the pair (arr[0], arr[2]) modifies arr[] to arr[] = { 1, 4, 3 } Since no p
7 min read
Maximum sum of pair values such that value of pairs of same group should be a multiple of i in range [1, N]
Given an array of pairs arr[] of size N, where the first element of the pair is the value of the pair and the second element is the group at which this pair belongs, the task is to find the maximum sum of pair values, such that the number of pairs of the same group should be a multiple of i for all i in the range [1, N]. Examples: Input: arr[] = {{
13 min read
Split array into minimum number of subsets such that elements of all pairs are present in different subsets at least once
Given an array arr[] consisting of N distinct integers, the task is to find the minimum number of times the array needs to be split into two subsets such that elements of each pair are present into two different subsets at least once. Examples: Input: arr[] = { 3, 4, 2, 1, 5 } Output: 3 Explanation: Possible pairs are { (1, 2), (1, 3), (1, 4), (1,
6 min read
Place N boys and M girls in different rows such that count of persons placed in each row is maximized
Given two integers N and M representing the number of boys and girls, the task is to arrange them in number of different rows of same size such that each row contains the maximum number of students possible and each row should contain either boys or girls.Note: No row can contain both boys and girls. Example: Input: N = 4, M = 2Output: 2Explanation
4 min read
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs
Given an integer K and a square matrix mat[][] of size N * N with elements from the range[1, K], the task is to count ways to remove pairs of distinct matrix elements such that remaining elements can be arranged in pairs vertically or horizontally. Examples: Input: mat[][] = {{1, 2}, {3, 4}}, K = 4Output: 4Explanation:Remove the row {1, 2}. Therefo
10 min read
Maximize remainder of sum of a pair of array elements with different parity modulo K
Given an array arr[] of size N, consisting of N / 2 even and odd integers each, and an integer K, the task is to find the maximum remainder of sum of a pair of array elements of different parity modulo K. Examples: Input: arr[] = {3, 2, 4, 11, 6, 7}, K = 7Output: 6Explanation: Sum of a pair of array elements = 2 + 11Sum % K = 13 % 7 = 6.Therefore,
7 min read
Maximum product of the remaining pair after repeatedly replacing pairs of adjacent array elements with their sum
Given an array arr[] of size N, the task is to find the maximum product of remaining pairs possible after repeatedly replacing a pair of adjacent array elements with their sum. Note: Reduce the array to a size of 2. Examples: Input: arr[] = {2, 3, 5, 6, 7}Output: 130Explanation:Replacing arr[1] and arr[2] with their sum (i.e. 3 + 5 = 8) modifies ar
8 min read
Find all pairs such that (X, Y) such that X^2 = Y and X < Y
Given an array arr[] of positive integers, the task is to find the count of all the pairs (X, Y) in the array such that X2=Y and Y>X. Examples: Input: arr[] = {2, 4, 8, 16, 9, 81, 3} Output: 4Explanation: There are 4 such pairs (2, 4), (4, 16), (9, 81), (3, 9) such that X2 = Y Input: arr[] = {2, 4, 16, 32, 1, 1, 1} Output: 2Explanation: There ar
5 min read
Find pair of rows in a binary matrix that has maximum bit difference
Given a Binary Matrix. The task is to find the pair of row in the Binary matrix that has maximum bit difference Examples: Input: mat[][] = {{1, 1, 1, 1}, {1, 1, 0, 1}, {0, 0, 0, 0}}; Output : (1, 3) Bit difference between row numbers 1 and 3 is maximum with value 4. Bit difference between 1 and 2 is 1 and between 2 and 3 is 3. Input: mat[][] = {{1
15 min read
Count pairs of substrings from a string S such that S1 does not occur after S2 in each pair
Given three strings str, str1 and str2, the task is to count the number of pairs of occurrences of str1 and str2 as a substring in the string str such that in each pair, the starting index of str1 is less than or equal to str2. Examples: Input: str = "geeksforgeeksfor", str1 = "geeks", str2 = "for" Output: 3 Explanation: Starting indices of str1 ar
7 min read
Check if there exists a pair (a, b) such that for all the N pairs either of the element should be equal to either a or b
Given an array arr[] of N pairs of distinct integers, the task is to check if there exists any pair (X, Y) such that each pair of the array has at least one common element with the pair (X, Y). Examples: Input: arr[] = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}Output: YesExplanation:One of the pair that satisfies the condition is (2, 4). Input: arr[] = {{1,
7 min read
Count of pairs in Array such that bitwise AND of XOR of pair and X is 0
Given an array arr[] consisting of N positive integers and a positive integer X, the task is to find the number of pairs (i, j) such that i < j and (arr[i]^arr[j] )&X is 0. Examples: Input: arr[] = {1, 3, 4, 2}, X = 2 Output: 2Explanation:Following are the possible pairs from the given array: (0, 2): The value of (arr[0]^arr[2])&X is (1^
11 min read
Maximum pair sum such that their digit sum are equal and divisible by K
Given a positive integer array arr[] of size N (1 ? N ? 105) and a positive integer K, the task is to find the maximum value of arr[i] + arr[j] by choosing two indices i and j, such that i != j, and the sum of digits of the element at arr[i] should be equal to arr[j] and are divisible by K. Examples: Input: arr = [18, 43, 36, 13, 7]Output: 54Explan
8 min read
Maximum pairs from given Graph where elements belong to different Connected Component
Given a graph with N vertices numbered from 0 to (N-1) and a matrix edges[][] representing the edges of the graph, the task is to find out the maximum number of pairs that can be formed where each element of a pair belongs to different connected components of the graph. Examples: Input: N = 4, edges = {{1, 2}, {2, 3}}Output: 3Explanation: Total nod
7 min read
Minimize sum of absolute difference between all pairs of array elements by decrementing and incrementing pairs by 1
Given an array arr[] ( 1-based indexing ) consisting of N integers, the task is to find the minimum sum of the absolute difference between all pairs of array elements by decrementing and incrementing any pair of elements by 1 any number of times. Examples: Input: arr[] = {1, 2, 3}Output: 0Explanation:Modify the array elements by performing the foll
5 min read
Find index of pair among given pairs with just greater average
Given an array of pairs arr[] of size N where the first value of all the pairs are distinct. For each pair of the given array find the index of another pair which have an average just greater than this one. Note: The average of two numbers a and b is defined as the floor ( a + b ) / 2. Examples: Input: { {2, 3}, {1, 3}, {3, 4} }Output: { 2, 2, -1}
11 min read
Count pairs such that difference between them and indices are different
Given an array arr[] of size N, the task is to count all pair of indices (i, j) such that i < j and j - i != arr[j] - arr[i]. Examples: Input: arr[] = {4, 1, 3, 3}Output: 5Explanation:The pair (0, 1) is a valid pair since 1 - 0 != 1 - 4.The pair (0, 2) is a valid pair since 2 - 0 != 3 - 4, 2 != -1.The pair (0, 3) is a valid pair since 3 - 0 != 3
7 min read
Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors
Given three integers N, M and K. The task is to find the number of ways to fill N positions using M colors such that there are exactly K pairs of different adjacent colors. Examples: Input: N = 3, M = 2, K = 1 Output: 4 Let the colors be 1 and 2, so the ways are: 1, 1, 2 1, 2, 2 2, 2, 1 2, 1, 1 The above 4 ways have exactly one pair of adjacent ele
12 min read
Minimum count of rows between rows containing X and Y respectively
Given a Grid of size NxM, and two integers X and Y, the task is to count the minimum number of rows between the row containing X and the row containing Y in such a way that the adjacent rows in between them have at least one element in common. Multiple occurrences of a number are allowed in the grid. In other words, two rows are said to be adjacent
14 min read
Find pair i, j such that |A[i]−A[j]| is same as sum of difference of them with any Array element
Given an array A[] having N non-negative integers, find a pair of indices i and j such that the absolute difference between them is same as the sum of differences of those with any other array element i.e., | A[i] − A[k] | + | A[k]− A[j] | = | A[i] − A[j] |, where k can be any index. Examples: Input: N = 3, A[] = {2, 7, 5}Output: 0 1Explanation:For
7 min read
Find pair of integers such that their sum is twice their Bitwise XOR
Given a positive integer N, the task is to find all pairs of integers (i, j) from the range [1, N] in increasing order of i such that: 1 ? i, j ? Ni + j = Ni + j = 2*(i ^ j)If there are no such pairs, return a pair {-1, -1}. Note: Here '^' denotes the bitwise XOR operation. Examples: Input: N = 4Output: {{1, 3}, {3, 1}}Explanation: A total of 3 pai
6 min read
2 Sum - Find a pair with given sum
Given an array of integers arr[] and an integer target, print a pair of two numbers such that they add up to target. You cannot use the same element twice. Examples: Input: arr[] = {2, 9, 10, 4, 15}, target = 12Output: {2, 10}Explanation: As sum of 2 and 10 is equal to 12. Input: arr[] = {3, 2, 4}, target = 8Output: { }Explanation: As no such pair
15+ min read
Minimum deletions to be done in given array such that every pair sum is a power of 2
Given an array arr[] consisting of N integers the task is to find the minimum number of elements that should be removed, such that for every remaining element arr[i], there exists another element arr[j], (i!=j) such that the sum of arr[i] and arr[j] is a power of 2. If after any number of deletions, no such pair exists, print -1. Examples: Input: a
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg