Skip to content
Related Articles

Related Articles

Find all Pairs possible from the given Array

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 13 Sep, 2022
Improve Article
Save Article

Given an array arr[] of N integers, the task is to find all the pairs possible from the given array. 
Note: 
 

  1. (arr[i], arr[i]) is also considered as a valid pair.
  2. (arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs.

Examples: 
 

Input: arr[] = {1, 2} 
Output: (1, 1), (1, 2), (2, 1), (2, 2).
Input: arr[] = {1, 2, 3} 
Output: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3) 
 

 

Approach: 
In order to find all the possible pairs from the array, we need to traverse the array and select the first element of the pair. Then we need to pair this element with all the elements in the array from index 0 to N-1. 
Below is the step by step approach: 
 

  • Traverse the array and select an element in each traversal.
  • For each element selected, traverse the array with help of another loop and form the pair of this element with each element in the array from the second loop.
  • The array in the second loop will get executed from its first element to its last element, i.e. from index 0 to N-1.
  • Print each pair formed.

Below is the implementation of the above approach:
 

C++




// C++ implementation to find all
// Pairs possible from the given Array
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all possible
// pairs from the array
void printPairs(int arr[], int n)
{
 
    // Nested loop for all possible pairs
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout << "(" << arr[i] << ", "
                 << arr[j] << ")"
                 << ", ";
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    printPairs(arr, n);
 
    return 0;
}

Java




// Java implementation to find all
// Pairs possible from the given Array
class GFG{
  
// Function to print all possible
// pairs from the array
static void printPairs(int arr[], int n)
{
  
    // Nested loop for all possible pairs
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            System.out.print("(" +  arr[i]+ ", "
                 + arr[j]+ ")"
                + ", ");
        }
    }
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2 };
    int n = arr.length;
  
    printPairs(arr, n);
  
}
}
 
// This code is contributed by PrinciRaj1992

Python3




# Python3 implementation to find all
# Pairs possible from the given Array
 
# Function to print all possible
# pairs from the array
def printPairs(arr, n):
 
    # Nested loop for all possible pairs
    for i in range(n):
        for j in range(n):
            print("(",arr[i],",",arr[j],")",end=", ")
 
# Driver code
 
arr=[1, 2]
n = len(arr)
 
printPairs(arr, n)
 
# This code is contributed by mohit kumar 29

C#




// C# implementation to find all
// Pairs possible from the given Array
using System;
 
class GFG{
  
// Function to print all possible
// pairs from the array
static void printPairs(int []arr, int n)
{
  
    // Nested loop for all possible pairs
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            Console.Write("(" +  arr[i]+ ", "
                 + arr[j]+ ")"
                + ", ");
        }
    }
}
  
// Driver code
public static void Main(string[] args)
{
    int []arr = { 1, 2 };
    int n = arr.Length;
  
    printPairs(arr, n);
}
}
 
// This code is contributed by AnkitRai01

Javascript




<script>
 
// Javascript implementation to find all
// Pairs possible from the given Array
 
// Function to print all possible
// pairs from the array
function printPairs(arr, n)
{
    // Nested loop for all possible pairs
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < n; j++) {
            document.write("(" + arr[i] + ", "
                 + arr[j] + ")"
                 + ", ");
        }
    }
}
 
// Driver code
var arr = [ 1, 2 ];
var n = arr.length;
printPairs(arr, n);
 
// This code is contributed by rutvik_56.
</script>

Output

(1, 1), (1, 2), (2, 1), (2, 2), 

Time Complexity: O(N2)

Auxiliary Space: O(1)
 

Using Merge Sort 

Approach : 

During the merge operation in merge sort we can get all the pairs and we can store those pairs into a vector of pairs. 

By just making few changes into the merge sort algorithm we can get all the pairs.

C++




/*
    This code was submitted by : Chirag Mittal from IIIT Dharwad ( username : iitjeechirag )
    storing all the pairs while merging
    Time Complexity : O(N logN)
    Space Complexity : O(N) + O(Number Of Pairs)
 
    using Merge Sort Algorithm
*/
 
#include<bits/stdc++.h>
using namespace std;
void getPairsMerge(int arr[],int l,int r,int mid,vector<pair<int,int>>&p){
    int b[l+r+1],i=l,k=l,j=mid+1;
    while(i<=mid && j<=r){
        if(arr[i]>arr[j]){
            b[k]=arr[j];
            p.push_back({arr[i],arr[j]});
            p.push_back({arr[j],arr[i]});
            p.push_back({arr[j],arr[j]});
            k++;
            j++;
        }
        else{
            p.push_back({arr[i],arr[j]});
            p.push_back({arr[j],arr[i]});
            p.push_back({arr[i],arr[i]});
            b[k]=arr[i];
            i++;
            k++;
        }
    }
 
    while(i<=mid){
        b[k]=arr[i];
        p.push_back({arr[i],arr[i]});
        i++;
        k++;
    }
    while(j<=r){
        b[k]=arr[j];
        p.push_back({arr[j],arr[j]});
        j++;
        k++;
    }
 
    for(int x=l;x<=r;x++){
        arr[x]=b[x];
    }
}
 
void getAllPairs(int arr[],int l,int r,vector<pair<int,int>>&p){
    if(l<r){
        int mid=(l+r)/2;
        getAllPairs(arr,l,mid,p);
        getAllPairs(arr,mid+1,r,p);
        getPairsMerge(arr,l,r,mid,p);
    }
}
 
int main(){
    int n=2;
    int arr[n]={1,2};
    vector<pair<int,int>>p;
    getAllPairs(arr,0,n-1,p);
    for(auto it:p){
        cout<<it.first<<" "<<it.second<<endl;
    }
}

Java




/*
    Java program that
    stores all the pairs while merging
    using Merge Sort Algorithm
    Time Complexity : O(N logN)
    Space Complexity : O(N) + O(Number Of Pairs)
*/
 
import java.util.*;
 
class GFG {
  static void
    getPairsMerge(int[] arr, int l, int r, int mid,
                  ArrayList<ArrayList<Integer> > p)
  {
    int[] b = new int[l + r + 1];
    int i = l, k = l, j = mid + 1;
    while (i <= mid && j <= r) {
      if (arr[i] > arr[j]) {
        b[k] = arr[j];
        ArrayList<Integer> a1
          = new ArrayList<Integer>();
        a1.add(arr[i]);
        a1.add(arr[j]);
 
        ArrayList<Integer> a2
          = new ArrayList<Integer>();
        a2.add(arr[j]);
        a2.add(arr[i]);
 
        ArrayList<Integer> a3
          = new ArrayList<Integer>();
        a3.add(arr[j]);
        a3.add(arr[j]);
 
        p.add(a1);
        p.add(a2);
        p.add(a3);
 
        k++;
        j++;
      }
      else {
 
        ArrayList<Integer> a1
          = new ArrayList<Integer>();
        a1.add(arr[i]);
        a1.add(arr[j]);
 
        ArrayList<Integer> a2
          = new ArrayList<Integer>();
        a2.add(arr[j]);
        a2.add(arr[i]);
 
        ArrayList<Integer> a3
          = new ArrayList<Integer>();
        a3.add(arr[i]);
        a3.add(arr[i]);
 
        p.add(a1);
        p.add(a2);
        p.add(a3);
 
        b[k] = arr[i];
        i++;
        k++;
      }
    }
 
    while (i <= mid) {
      b[k] = arr[i];
      ArrayList<Integer> a3
        = new ArrayList<Integer>();
      a3.add(arr[i]);
      a3.add(arr[i]);
 
      p.add(a3);
      i++;
      k++;
    }
    while (j <= r) {
      b[k] = arr[j];
      ArrayList<Integer> a3
        = new ArrayList<Integer>();
      a3.add(arr[j]);
      a3.add(arr[j]);
 
      p.add(a3);
      j++;
      k++;
    }
 
    for (int x = l; x <= r; x++) {
      arr[x] = b[x];
    }
  }
 
  static void
    getAllPairs(int[] arr, int l, int r,
                ArrayList<ArrayList<Integer> > p)
  {
    if (l < r) {
      int mid = (l + r) / 2;
      getAllPairs(arr, l, mid, p);
      getAllPairs(arr, mid + 1, r, p);
      getPairsMerge(arr, l, r, mid, p);
    }
  }
 
  public static void main(String[] args)
  {
    int n = 2;
    int[] arr = { 1, 2 };
    ArrayList<ArrayList<Integer> > p
      = new ArrayList<ArrayList<Integer> >();
    getAllPairs(arr, 0, n - 1, p);
    for (ArrayList<Integer> it : p)
      System.out.println(it.get(0) + " " + it.get(1));
  }
}
 
// This code is contributed by phasing17

Python3




'''
    Python3 program to store all the pairs while merging
    using Merge Sort Algorithm
     
'''
 
# Function to perform merge sort
# Time Complexity : O(N logN)
# Space Complexity : O(N) + O(Number Of Pairs)
def getPairsMerge(arr, l, r, mid, p):
     
    b = [0 for _ in range(l + r + 1)]
    i=l
    k=l
    j=mid+1;
    while(i<=mid and j<=r):
        if(arr[i]>arr[j]):
            b[k]=arr[j];
            p.append([arr[i],arr[j]]);
            p.append([arr[j],arr[i]]);
            p.append([arr[j],arr[j]]);
            k+= 1;
            j+= 1;
         
        else:
            p.append([arr[i],arr[j]]);
            p.append([arr[j],arr[i]]);
            p.append([arr[i],arr[i]]);
            b[k]=arr[i];
            i+= 1;
            k+= 1;
         
     
 
    while(i<=mid):
        b[k]=arr[i];
        p.append([arr[i],arr[i]]);
        i+= 1;
        k+= 1;
     
    while(j<=r):
        b[k]=arr[j];
        p.append([arr[j],arr[j]]);
        j+= 1;
        k+= 1;
     
    for x in range(l, r + 1):
        arr[x]=b[x];
     
 
 
# Function to get all pairs
def getAllPairs(arr, l, r, p):
 
    if(l<r):
        mid=int((l+r)/2);
        getAllPairs(arr,l,mid,p);
        getAllPairs(arr,mid+1,r,p);
        getPairsMerge(arr,l,r,mid,p);
 
 
# Driver code
 
n=2;
arr = [0 for _ in range(n)]
arr[0] = 1;
arr[1] = 2;
p = [];
getAllPairs(arr,0,n-1,p);
 
# Displaying the sorted pairs
for it in p:
    print(it[0], it[1])
 
 
# This code is contributed by phasing17

C#




/*
    C# program that
    stores all the pairs while merging
    using Merge Sort Algorithm
    Time Complexity : O(N logN)
    Space Complexity : O(N) + O(Number Of Pairs)
*/
 
using System;
using System.Collections.Generic;
 
class GFG {
  static void getPairsMerge(int[] arr, int l, int r,
                            int mid, List<int[]> p)
  {
    int[] b = new int[l + r + 1];
    int i = l, k = l, j = mid + 1;
    while (i <= mid && j <= r) {
      if (arr[i] > arr[j]) {
        b[k] = arr[j];
        p.Add(new[] { arr[i], arr[j] });
        p.Add(new[] { arr[j], arr[i] });
        p.Add(new[] { arr[j], arr[j] });
        k++;
        j++;
      }
      else {
        p.Add(new[] { arr[i], arr[j] });
        p.Add(new[] { arr[j], arr[i] });
        p.Add(new[] { arr[i], arr[i] });
        b[k] = arr[i];
        i++;
        k++;
      }
    }
 
    while (i <= mid) {
      b[k] = arr[i];
      p.Add(new[] { arr[i], arr[i] });
      i++;
      k++;
    }
    while (j <= r) {
      b[k] = arr[j];
      p.Add(new[] { arr[j], arr[j] });
      j++;
      k++;
    }
 
    for (int x = l; x <= r; x++) {
      arr[x] = b[x];
    }
  }
 
  static void getAllPairs(int[] arr, int l, int r,
                          List<int[]> p)
  {
    if (l < r) {
      int mid = (l + r) / 2;
      getAllPairs(arr, l, mid, p);
      getAllPairs(arr, mid + 1, r, p);
      getPairsMerge(arr, l, r, mid, p);
    }
  }
 
  public static void Main(string[] args)
  {
    int n = 2;
    int[] arr = { 1, 2 };
    List<int[]> p = new List<int[]>();
    getAllPairs(arr, 0, n - 1, p);
    foreach(var it in p)
      Console.WriteLine(it[0] + " " + it[1]);
  }
}
 
// This code is contributed by phasing17

Javascript




/*
    JavaScript program to store all the pairs while merging
    using Merge Sort Algorithm
*/
 
// Function to perform merge sort
// Time Complexity : O(N logN)
// Space Complexity : O(N) + O(Number Of Pairs)
function getPairsMerge(arr, l, r, mid, p)
{
    let b = new Array(l+r+1).fill(0);
    let i=l,k=l,j=mid+1;
    while(i<=mid && j<=r){
        if(arr[i]>arr[j]){
            b[k]=arr[j];
            p.push([arr[i],arr[j]]);
            p.push([arr[j],arr[i]]);
            p.push([arr[j],arr[j]]);
            k++;
            j++;
        }
        else{
            p.push([arr[i],arr[j]]);
            p.push([arr[j],arr[i]]);
            p.push([arr[i],arr[i]]);
            b[k]=arr[i];
            i++;
            k++;
        }
    }
 
    while(i<=mid){
        b[k]=arr[i];
        p.push([arr[i],arr[i]]);
        i++;
        k++;
    }
    while(j<=r){
        b[k]=arr[j];
        p.push([arr[j],arr[j]]);
        j++;
        k++;
    }
 
    for(let x=l;x<=r;x++){
        arr[x]=b[x];
    }
}
 
// Function to get all pairs
function getAllPairs(arr, l, r, p)
{
    if(l<r){
        let mid= Math.floor((l+r)/2);
        getAllPairs(arr,l,mid,p);
        getAllPairs(arr,mid+1,r,p);
        getPairsMerge(arr,l,r,mid,p);
    }
}
 
 
// Driver code
 
let n=2;
let arr = new Array(n).fill(0);
arr[0] = 1;
arr[1] = 2;
let p = [];
getAllPairs(arr,0,n-1,p);
 
// Displaying the sorted pairs
for(var it of p)
    console.log(it[0], it[1])
 
 
// This code is contributed by phasing17

Output

1 2
2 1
1 1
2 2

Time Complexity : O (N LogN )

Auxiliary Space: O(l + r)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!