The Wayback Machine - https://web.archive.org/web/20240928070500/https://www.geeksforgeeks.org/find-a-pair-with-the-given-difference/
Open In App

Find a pair with the given difference

Last Updated : 08 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
27.25%
2.5L

Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. 
Examples: 

Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78
Output: Pair Found: (2, 80)

Input: arr[] = {90, 70, 20, 80, 50}, n = 45
Output: No Such Pair

Method 1: The simplest method is to run two loops, the outer loop picks the first element (smaller element) and the inner loop looks for the element picked by outer loop plus n. Time complexity of this method is O(n2).

Algorithm:

  1.    Start iterating through each element of the array using an outer loop.
  2.    For each element, start iterating again through each of the elements of the array except the one picked in outer loop using an inner loop.
  3.    If the difference between the current element and any of the elements of it is equal to the given difference, print both elements.
  4.    Continue the process until all possible pairs of elements are compared.
  5.    If no pair found, print “No such pair”.

Below is the implementation of the approach:

C++
// C++ code for the approach

#include<bits/stdc++.h>
using namespace std;

// Function to find if there exists a pair 
// of elements in the array whose difference is n
void findPair(int arr[], int n, int diff) {
    // Nested loop to compare all possible 
      // pairs of elements
    for(int i=0; i<n; i++) {
        for(int j=0; j<n; j++) {
              if(i == j)
                  continue;
          
            // If the difference between the 
              // two elements is n, print them
            if((arr[j] - arr[i]) == diff) {
                cout << "Pair Found: (" << arr[i] << ", " << arr[j] << ")";
                  return;
            }
        }
    }
  
      cout << "No such pair";
}

int main() {
      // Input array and diff
    int arr[] = { 1, 8, 30, 40, 100 };
    int n = sizeof(arr)/sizeof(arr[0]);
    int diff = -60;
      
      // Function call
    findPair(arr, n, diff);
    return 0;
}
Java
import java.util.Arrays;

public class FindPairWithDifference {
    
    // Function to find if there exists a pair
    // of elements in the array whose difference is n
    static void findPair(int[] arr, int n, int diff) {
        // Nested loop to compare all possible
        // pairs of elements
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j)
                    continue;

                // If the difference between the
                // two elements is n, print them
                if ((arr[j] - arr[i]) == diff) {
                    System.out.println("Pair Found: (" + arr[i] + ", " + arr[j] + ")");
                    return;
                }
            }
        }

        System.out.println("No such pair");
    }

    public static void main(String[] args) {
        // Input array and diff
        int[] arr = { 1, 8, 30, 40, 100 };
        int n = arr.length;
        int diff = -60;

        // Function call
        findPair(arr, n, diff);
    }
}
Python
# Function to find if there exists a pair
# of elements in the array whose difference is n
def find_pair(arr, n, diff):
    # Nested loop to compare all possible
    # pairs of elements
    for i in range(n):
        for j in range(n):
            if i == j:
                continue
            
            # If the difference between the
            # two elements is n, print them
            if arr[j] - arr[i] == diff:
                print(f"Pair Found: ({arr[i]}, {arr[j]})")
                return
    
    print("No such pair")

# Input array and diff
arr = [1, 8, 30, 40, 100]
n = len(arr)
diff = -60

# Function call
find_pair(arr, n, diff)
C#
using System;

class MainClass {
    // Function to find if there exists a pair 
    // of elements in the array whose difference is n
    static void FindPair(int[] arr, int n, int diff) {
        // Nested loop to compare all possible pairs of elements
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j)
                    continue;

                // If the difference between the two elements is n, print them
                if ((arr[j] - arr[i]) == diff) {
                    Console.WriteLine($"Pair Found: ({arr[i]}, {arr[j]})");
                    return;
                }
            }
        }

        Console.WriteLine("No such pair");
    }

    public static void Main (string[] args) {
        // Input array and diff
        int[] arr = { 1, 8, 30, 40, 100 };
        int n = arr.Length;
        int diff = -60;

        // Function call
        FindPair(arr, n, diff);
    }
}
JavaScript
function findPair(arr, diff) {
  // Nested loop to compare 
  // all  possible pairs of elements
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (i === j) {
        continue;
      }
      // If the difference between the two elements is 'diff' 
      // print them and return
      if (arr[j] - arr[i] === diff) {
        console.log(`Pair Found: (${arr[i]}, ${arr[j]})`);
        return;
      }
    }
  }
  console.log('No such pair');
}

// Input array and 'diff'
const arr = [1, 8, 30, 40, 100];
const diff = -60;
// Function call
findPair(arr, diff);

Output
Pair Found: (100, 40)

Time Complexity: O(n*n) as two nested for loops are executing both from 1 to n where n is size of input array.
Space Complexity: O(1) as no extra space has been taken.

Method 2: We can use sorting and Binary Search to improve time complexity to O(nLogn). The first step is to sort the array in ascending order. Once the array is sorted, traverse the array from left to right, and for each element arr[i], binary search for arr[i] + n in arr[i+1..n-1]. If the element is found, return the pair. Both first and second steps take O(nLogn). So overall complexity is O(nLogn). 
Method 3: The second step of the Method -2 can be improved to O(n). The first step remains the same. The idea for the second step is to take two index variables i and j, and initialize them as 0 and 1 respectively. Now run a linear loop. If arr[j] – arr[i] is smaller than n, we need to look for greater arr[j], so increment j. If arr[j] – arr[i] is greater than n, we need to look for greater arr[i], so increment i. Thanks to Aashish Barnwal for suggesting this approach. 
The following code is only for the second step of the algorithm, it assumes that the array is already sorted.  

C++
// C++ program to find a pair with the given difference 
#include <bits/stdc++.h>
using namespace std;

// The function assumes that the array is sorted 
bool findPair(int arr[], int size, int n) 
{ 
    // Initialize positions of two elements 
    int i = 0; 
    int j = 1; 

    // Search for a pair 
    while (i < size && j < size) 
    { 
        if (i != j && (arr[j] - arr[i] == n || arr[i] - arr[j] == n) )
        { 
            cout << "Pair Found: (" << arr[i] <<
                        ", " << arr[j] << ")"; 
            return true; 
        } 
        else if (arr[j]-arr[i] < n) 
            j++; 
        else
            i++; 
    } 

    cout << "No such pair"; 
    return false; 
} 

// Driver program to test above function 
int main() 
{ 
    int arr[] = {1, 8, 30, 40, 100}; 
    int size = sizeof(arr)/sizeof(arr[0]); 
    int n = -60; 
    findPair(arr, size, n); 
    return 0; 
} 

// This is code is contributed by rathbhupendra
C
// C program to find a pair with the given difference
#include <stdio.h>

// The function assumes that the array is sorted 
int findPair(int arr[], int size, int n)
{
    // Initialize positions of two elements
    int i = 0;  
    int j = 1;

    // Search for a pair
    while (i<size && j<size)
    {
        if (i != j && (arr[j] - arr[i] == n || arr[i] - arr[j] == n))
        {
            printf("Pair Found: (%d, %d)", arr[i], arr[j]);
            return 1;
        }
        else if (arr[j]-arr[i] < n)
            j++;
        else
            i++;
    }

    printf("No such pair");
    return 0;
}

// Driver program to test above function
int main()
{
    int arr[] = {1, 8, 30, 40, 100};
    int size = sizeof(arr)/sizeof(arr[0]);
    int n = -60;
    findPair(arr, size, n);
    return 0;
}
Java
// Java program to find a pair with the given difference
import java.io.*;

class PairDifference
{
    // The function assumes that the array is sorted
    static boolean findPair(int arr[],int n)
    {
        int size = arr.length;

        // Initialize positions of two elements
        int i = 0, j = 1;

        // Search for a pair
        while (i < size && j < size)
        {
            if (i != j && (arr[j] - arr[i] == n || arr[i] - arr[j] == n))
            {
                System.out.print("Pair Found: "+
                                 "( "+arr[i]+", "+ arr[j]+" )");
                return true;
            }
            else if (arr[j] - arr[i] < n)
                j++;
            else
                i++;
        }

        System.out.print("No such pair");
        return false;
    }

    // Driver program to test above function
    public static void main (String[] args)
    {
        int arr[] = {1, 8, 30, 40, 100};
        int n = -60;
        findPair(arr,n);
    }
}
/*This code is contributed by Devesh Agrawal*/
Python
# Python program to find a pair with the given difference

# The function assumes that the array is sorted
def findPair(arr,n):

    size = len(arr)

    # Initialize positions of two elements
    i,j = 0,1

    # Search for a pair
    while i < size and j < size:

        if i != j and arr[j]-arr[i] == n:
            print "Pair found (",arr[i],",",arr[j],")"
            return True

        elif arr[j] - arr[i] < n:
            j+=1
        else:
            i+=1
    print "No pair found"
    return False

# Driver function to test above function
arr = [1, 8, 30, 40, 100]
n = 60
findPair(arr, n)

# This code is contributed by Devesh Agrawal
C#
// C# program to find a pair with the given difference
using System;

class GFG {
    
    // The function assumes that the array is sorted
    static bool findPair(int []arr, int n)
    {
        int size = arr.Length;

        // Initialize positions of two elements
        int i = 0, j = 1;

        // Search for a pair
        while (i < size && j < size)
        {
            if (i != j && arr[j] - arr[i] == n)
            {
                Console.Write("Pair Found: " 
                + "( " + arr[i] + ", " + arr[j] +" )");
                
                return true;
            }
            else if (arr[j] - arr[i] < n)
                j++;
            else
                i++;
        }

        Console.Write("No such pair");
        
        return false;
    }

    // Driver program to test above function
    public static void Main ()
    {
        int []arr = {1, 8, 30, 40, 100};
        int n = 60;
        
        findPair(arr, n);
    }
}

// This code is contributed by Sam007.
JavaScript
 <script>
 
        // JavaScript program for the above approach

        // The function assumes that the array is sorted 
        function findPair(arr, size, n) {
            // Initialize positions of two elements 
            let i = 0;
            let j = 1;

            // Search for a pair 
            while (i < size && j < size) {
                if (i != j && arr[j] - arr[i] == n) {
                    document.write("Pair Found: (" + arr[i] + ", " +
                    arr[j] + ")");
                    return true;
                }
                else if (arr[j] - arr[i] < n)
                    j++;
                else
                    i++;
            }

            document.write("No such pair");
            return false;
        }

        // Driver program to test above function 

        let arr = [1, 8, 30, 40, 100];
        let size = arr.length;
        let n = 60;
        findPair(arr, size, n);


    // This code is contributed by Potta Lokesh
  
    </script>
PHP
<?php 
// PHP program to find a pair with
// the given difference

// The function assumes that the 
// array is sorted 
function findPair(&$arr, $size, $n)
{
    // Initialize positions of 
    // two elements
    $i = 0; 
    $j = 1;

    // Search for a pair
    while ($i < $size && $j < $size)
    {
        if ($i != $j && $arr[$j] - 
                        $arr[$i] == $n)
        {
            echo "Pair Found: " . "(" . 
                  $arr[$i] . ", " . $arr[$j] . ")";
            return true;
        }
        else if ($arr[$j] - $arr[$i] < $n)
            $j++;
        else
            $i++;
    }

    echo "No such pair";
    return false;
}

// Driver Code
$arr = array(1, 8, 30, 40, 100);
$size = sizeof($arr);
$n = 60;
findPair($arr, $size, $n);

// This code is contributed 
// by ChitraNayal
?>

Output
Pair Found: (100, 40)

Time Complexity: O(n*log(n)) [Sorting is still required as first step], Where n is number of element in given array
Auxiliary Space: O(1)

The above code can be simplified and can be made more understandable by reducing bunch of If-Else checks . Thanks to Nakshatra Chhillar for suggesting this simplification. We will understand simplifications through following code:

C++
// C++ program to find a pair with the given difference
#include <bits/stdc++.h>
using namespace std;
bool findPair(int arr[], int size, int n)
{
    // Step-1 Sort the array
    sort(arr, arr + size);

    // Initialize positions of two elements
    int l = 0;
    int r = 1;

    // take absolute value of difference
    // this does not affect the pair as A-B=diff is same as
    // B-A= -diff
    n = abs(n);

    // Search for a pair

    // These loop running conditions are sufficient
    while (l <= r and r < size) {
        int diff = arr[r] - arr[l];
        if (diff == n
            and l != r) // we need distinct elements in pair
                        // so l!=r
        {
            cout << "Pair Found: (" << arr[l] << ", "
                 << arr[r] << ")";
            return true;
        }
        else if (diff > n) // try to reduce the diff
            l++;
        else // Note if l==r then r will be advanced thus no
             // pair will be missed
            r++;
    }
    cout << "No such pair";
    return false;
}

// Driver program to test above function
int main()
{
    int arr[] = { 1, 8, 30, 40, 100 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int n = -60;
    findPair(arr, size, n);
    cout << endl;
    n = 20;
    findPair(arr, size, n);
    return 0;
}

// This code is contributed by Nakshatra Chhillar
Java
// Java program to find a pair with the given difference
import java.io.*;
import java.util.Arrays;
 
class GFG {
static boolean findPair(int arr[], int size, int n)
{
    // Step-1 Sort the array
    Arrays.sort(arr);

    // Initialize positions of two elements
    int l = 0;
    int r = 1;

    // take absolute value of difference
    // this does not affect the pair as A-B=diff is same as
    // B-A= -diff
    n = Math.abs(n);

    // Search for a pair

    // These loop running conditions are sufficient
    while (l <= r && r < size) {
        int diff = arr[r] - arr[l];
        if (diff == n
            && l != r) // we need distinct elements in pair
                        // so l!=r
        {
            System.out.print("Pair Found: (" + arr[l] + ", "
                + arr[r] + ")");
            return true;
        }
        else if (diff > n) // try to reduce the diff
            l++;
        else // Note if l==r then r will be advanced thus no
            // pair will be missed
            r++;
    }
    System.out.print("No such pair");
    return false;
}

// Driver program to test above function
public static void main (String[] args) 
{
    int arr[] = { 1, 8, 30, 40, 100 };
    int size = arr.length;
    int n = -60;
    findPair(arr, size, n);
    System.out.println();
    n = 20;
    findPair(arr, size, n);
}
}

// This code is contributed by Pushpesh Raj
Python
# Python program to find a pair with the given difference
def findPair( arr, size, n):
    # Step-1 Sort the array
    arr.sort();
    
    # Initialize positions of two elements
    l = 0;
    r = 1;

    # take absolute value of difference
    # this does not affect the pair as A-B=diff is same as
    # B-A= -diff
    n = abs(n);

    # Search for a pair

    # These loop running conditions are sufficient
    while (l <= r and r < size) :
        diff = arr[r] - arr[l];
        if (diff == n and l != r): 
        # we need distinct elements in pair
        # so l!=r
            print("Pair Found: (" , arr[l] , ", "
                 , arr[r] , ")");
            return True;

        elif (diff > n):# try to reduce the diff
            l += 1;
        else :# Note if l==r then r will be advanced thus no
             # pair will be missed
            r+=1;

    print("No such pair");
    return False;

# Driver program to test above function
arr = [ 1, 8, 30, 40, 100 ];
size = len(arr);
n = -60;
findPair(arr, size, n);
n = 20;
findPair(arr, size, n);

# This code is contributed by agrawalpoojaa976.
C#
// C# code implementation
using System;
using System.Collections;
public class GFG
{

  static bool findPair(int[] arr, int size, int n)
  {

    // Step-1 Sort the array
    Array.Sort(arr);

    // Initialize positions of two elements
    int l = 0;
    int r = 1;

    // take absolute value of difference
    // this does not affect the pair as A-B=diff is same
    // as B-A= -diff
    n = Math.Abs(n);

    // Search for a pair

    // These loop running conditions are sufficient
    while (l <= r && r < size) {
      int diff = arr[r] - arr[l];
      if (diff == n
          && l != r) // we need distinct elements in
        // pair so l!=r
      {
        Console.Write("Pair Found: (" + arr[l]
                      + ", " + arr[r] + ")");
        return true;
      }
      else if (diff > n) // try to reduce the diff
        l++;
      else // Note if l==r then r will be advanced
        // thus no
        // pair will be missed
        r++;
    }
    Console.Write("No such pair");
    return false;
  }

  static public void Main()
  {

    // Code
    int[] arr = { 1, 8, 30, 40, 100 };
    int size = arr.Length;
    int n = -60;
    findPair(arr, size, n);
    Console.WriteLine();
    n = 20;
    findPair(arr, size, n);
  }
}

// This code is contributed by lokesh.
JavaScript
// JavaScript program to find a pair with the given difference

const findPair = (arr, size, n) => {
    // Step-1 Sort the array
    arr.sort((a, b) => a - b);

    // Initialize positions of two elements
    let l = 0;
    let r = 1;

    // take absolute value of difference
    // this does not affect the pair as A-B=diff is same as
    // B-A= -diff
    n = Math.abs(n);

    // Search for a pair

    // These loop running conditions are sufficient
    while (l <= r && r < size) {
        let diff = arr[r] - arr[l];
        if (diff === n
            && l !== r) // we need distinct elements in pair
                        // so l!==r
        {
            console.log("Pair Found: (" + arr[l] + ", "
                + arr[r] + ")");
            return true;
        }
        else if (diff > n) // try to reduce the diff
            l++;
        else // Note if l==r then r will be advanced thus no
             // pair will be missed
            r++;
    }
    console.log("No such pair");
    return false;
}

// Driver program to test above function
const main = () => {
    let arr = [1, 8, 30, 40, 100];
    let size = arr.length;
    let n = -60;
    findPair(arr, size, n);
    console.log();
    n = 20;
    findPair(arr, size, n);
}

main();

Output
Pair Found: (40, 100)
No such pair

Time Complexity: O(n*log(n)) [Sorting is still required as first step], Where n is number of element in given array
Auxiliary Space: O(1)

Method 4 :Hashing can also be used to solve this problem. Create an empty hash table HT. Traverse the array, use array elements as hash keys and enter them in HT. Traverse the array again look for value n + arr[i] in HT. 

C++
// C++ program to find a pair with the given difference
#include <bits/stdc++.h>
using namespace std;

// The function assumes that the array is sorted
bool findPair(int arr[], int size, int n)
{
    unordered_map<int, int> mpp;
    for (int i = 0; i < size; i++) {
        mpp[arr[i]]++;

        // Check if any element whose frequency
        // is greater than 1 exist or not for n == 0
        if (n == 0 && mpp[arr[i]] > 1)
            return true;
    }

    // Check if difference is zero and
    // we are unable to find any duplicate or
    // element whose frequency is greater than 1
    // then no such pair found.
    if (n == 0)
        return false;

    for (int i = 0; i < size; i++) {
        if (mpp.find(n + arr[i]) != mpp.end()) {
            cout << "Pair Found: (" << arr[i] << ", "
                 << n + arr[i] << ")";
            return true;
        }
    }

    cout << "No Pair found";
    return false;
}

// Driver program to test above function
int main()
{
    int arr[] = { 1, 8, 30, 40, 100 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int n = -60;
    findPair(arr, size, n);
    return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;

class GFG
{

  // The function assumes that the array is sorted
  static boolean findPair(int[] arr, int size, int n)
  {
    HashMap<Integer,
            Integer> mpp = new HashMap<Integer,
                                      Integer>();

     // Traverse the array
    for(int i = 0; i < size; i++)
    {
         
        // Update frequency
        // of arr[i]
        mpp.put(arr[i],
               mpp.getOrDefault(arr[i], 0) + 1);
      
        // Check if any element whose frequency
        // is greater than 1 exist or not for n == 0
        if (n == 0 && mpp.get(arr[i]) > 1)
            return true;
    }
 
     // Check if difference is zero and
    // we are unable to find any duplicate or
    // element whose frequency is greater than 1
    // then no such pair found.
    if (n == 0)
        return false;

    for (int i = 0; i < size; i++) {
      if (mpp.containsKey(n + arr[i])) {
        System.out.print("Pair Found: (" + arr[i] + ", " +
                      + (n + arr[i]) + ")");
        return true;
      }
    }
    System.out.print("No Pair found");
    return false;
  }


// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 8, 30, 40, 100 };
    int size = arr.length;
    int n = -60;
    findPair(arr, size, n);
}
}

// This code is contributed by code_hunt.
Python
# Python program to find a pair with the given difference

# The function assumes that the array is sorted
def findPair(arr, size, n):
    mpp = {}

    for i in range(size):
        if arr[i] in mpp:
            mpp[arr[i]] += 1
            if n == 0 and mpp[arr[i]] > 1:
                print("Pair Found: (" + str(arr[i]) + ", " + str(arr[i]) + ")")
                return True
        else:
            mpp[arr[i]] = 1

    if n == 0:
        return False

    for i in range(size):
        if n + arr[i] in mpp:
            print("Pair Found: (" + str(arr[i]) + ", " + str(n + arr[i]) + ")")
            return True

    print("No Pair found")
    return False

# Driver program to test the above function
arr = [1, 8, 30, 40, 100]
size = len(arr)
n = -60
findPair(arr, size, n)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;

public class GFG
{

// The function assumes that the array is sorted
static bool findPair(int[] arr, int size, int n)
{
    Dictionary<int, int> mpp = new Dictionary<int, int>();

    // Traverse the array
    for(int i = 0; i < size; i++)
    {
        
        // Update frequency
        // of arr[i]
        mpp[arr[i]]=mpp.GetValueOrDefault(arr[i], 0) + 1;
    
        // Check if any element whose frequency
        // is greater than 1 exist or not for n == 0
        if (n == 0 && mpp[arr[i]] > 1)
            return true;
    }

    // Check if difference is zero and
    // we are unable to find any duplicate or
    // element whose frequency is greater than 1
    // then no such pair found.
    if (n == 0)
        return false;

    for (int i = 0; i < size; i++) {
    if (mpp.ContainsKey(n + arr[i])) {
        Console.WriteLine("Pair Found: (" + arr[i] + ", " +
                    + (n + arr[i]) + ")");
        return true;
    }
    }
    Console.WriteLine("No Pair found");
    return false;
}

// Driver Code
public static void Main(string []args) 
{
    int[] arr = { 1, 8, 30, 40, 100 };
    int size = arr.Length;
    int n = -60;
    findPair(arr, size, n);
}
}

// This code is contributed by Aman Kumar
JavaScript
<script>
// Javascript program for the above approach

// The function assumes that the array is sorted
function findPair(arr, size, n) {
  let mpp = new Map();

  // Traverse the array
  for (let i = 0; i < size; i++) {

    // Update frequency
    // of arr[i]
    if (mpp.has(arr[i]))
      mpp.set(arr[i], mpp.get(arr[i]) + 1);
    else
      mpp.set(arr[i], 1)

    // Check if any element whose frequency
    // is greater than 1 exist or not for n == 0
    if (n == 0 && mpp.get(arr[i]) > 1)
      return true;
  }

  // Check if difference is zero and
  // we are unable to find any duplicate or
  // element whose frequency is greater than 1
  // then no such pair found.
  if (n == 0)
    return false;

  for (let i = 0; i < size; i++) {
    if (mpp.has(n + arr[i])) {
      document.write("Pair Found: (" + arr[i] + ", " +
        + (n + arr[i]) + ")");
      return true;
    }
  }
  document.write("No Pair found");
  return false;
}

// Driver Code
let arr = [1, 8, 30, 40, 100];
let size = arr.length;
let n = -60;
findPair(arr, size, n);

// This code is contributed by Saurabh Jaiswal
</script>

Output
Pair Found: (100, 40)

Time Complexity: O(n), Where n is number of element in given array
Auxiliary Space: O(n)
 


Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
 



Previous Article
Next Article

Similar Reads

Queries to check if any pair exists in an array having values at most equal to the given pair
Given a vector of pairs arr[] and Q queries in the form of pairs in an array Queries[], the task for each query is to check if there exists any pair with both the values smaller than those in the pair of the current query. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[][] = {{3, 5}, {2, 7}, {2, 3}, {4, 9}}, Quer
12 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
Probability of a random pair being the maximum weighted pair
Given two arrays A and B, a random pair is picked having an element from array A and another from array B. Output the probability of the pair being maximum weighted. Examples: Input : A[] = 1 2 3 B[] = 1 3 3 Output : 0.222 Explanation : Possible pairs are : {1, 1}, {1, 3}, {1, 3}, {2, 1}, {2, 3}, {2, 3}, {3, 1}, {3, 3}, {3, 3} i.e. 9. The pair with
7 min read
Count of quadruples with product of a pair equal to the product of the remaining pair
Given an array arr[] of size N, the task is to count the number of unique quadruples (a, b, c, d) from the array such that the product of any pair of elements of the quadruple is equal to the product of the remaining pair of elements. Examples: Input: arr[] = {2, 3, 4, 6}Output: 8Explanation:There are 8 quadruples in the array, i.e. (2, 6, 3, 4), (
7 min read
Pair the integers of Array so that each pair sum is consecutive and distinct
Given an array arr[]of size N. We have to pair the integers such that each integer should be in exactly one pair and each sum of pairs is consecutive and distinct. Formally, sum(arri + arrj) + 1 = sum(arri1 + arrj1). Print the pairs of integers satisfying all the conditions. If it is not possible to find the pairs return -1. Examples: Input: N = 6,
7 min read
Reduce Binary Array by replacing both 0s or both 1s pair with 0 and 10 or 01 pair with 1
Given a binary array arr[] of size N, the task is to find the last number remaining in the array after performing a set of operations. In each operation, select any two numbers and perform the following: If both numbers are the same, remove them from the array and insert a 0.If both numbers are different, remove both of them and insert a 1.Example:
9 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 a Co-Prime pair with maximum difference in a given range
Given two integers L and R, where L < R, the task is to find Co-prime numbers X and Y such that L <= X < Y <= R and the difference between X and Y is maximum i.e., maximize (Y - X) over all pairs between L and R where GCD(X, Y) = 1. Note: Co-prime numbers are the numbers whose GCD (Greatest Common Divisor) is 1 i.e., A and B are Co-prim
6 min read
Find minimum difference between any two elements (pair) in given array
Given an unsorted array, find the minimum difference between any pair in the given array. Examples : Input: {1, 5, 3, 19, 18, 25}Output: 1Explanation: Minimum difference is between 18 and 19 Input: {30, 5, 20, 9}Output: 4Explanation: Minimum difference is between 5 and 9 Input: {1, 19, -4, 31, 38, 25, 100}Output: 5Explanation: Minimum difference is
15+ min read
Javascript Program to Find a pair with the given difference
Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78Output: Pair Found: (2, 80)Input: arr[] = {90, 70, 20, 80, 50}, n = 45Output: No Such PairNative Approach:The simplest method is to run two loops, the outer loop picks the first el
4 min read
Minimum groups to split Array such that their each pair value difference and position difference are same
Given an array arr[] consisting of N integers, the task is to split the array into the minimum number of disjoint groups, such that differences between any pair of the elements in a group are equal to the difference between their positions in that group. Examples: Input: arr[] = {30, 32, 44, 31, 45, 32, 31, 33}Output: 3Explanation:The one possible
7 min read
Find pair with maximum difference in any column of a Matrix
Given a N*N matrix of positive integers. The task is to find the maximum difference between any pair of elements in any column of the matrix. Examples: Input : mat[N][N] = { { 1, 2, 3, 4, 5 }, { 5, 3, 5, 4, 0 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Max difference : 12 5th column has the pair with max difference (0,
6 min read
Find a pair with sum N having minimum absolute difference
Given an integer N, the task is to find a distinct pair of X and Y such that X + Y = N and abs(X - Y) is minimum. Examples: Input: N = 11Output: 5 6 Explanation:X = 5 and Y = 6 satisfy the given equation. Therefore, the minimum absolute value of abs(X - Y) = 1. Input: N = 12 Output: 5 7 Naive Approach: The simplest approach to solve this problem is
6 min read
Find minimum K such that difference between any Array pair is not a multiple of K
Given an array arr[] of length N. Find a positive integer K such that the difference between any pair of array elements is not a multiple of K. Examples: Input: arr[] = {11, 20, 13}Output: 4?Explanation: The possible differences are A1 ? A2 = 9, A1 ? A3 = 2 , and A2 ? A3 = 7. The least positive integer not a multiple of any of these differences is
7 min read
Find pair of consecutive Perfect Squares with difference K
Given an integer K, the task is to find two consecutive perfect squares whose difference is K. If there don't exist any such pairs of numbers, then print -1. Examples: Input: K = 5Output: 4 9Explanation:So, 4 and 9 are the two perfect squares which differ by 5(= 9 - 4 = 5). Input: K = 4Output: -1 Naive Approach: The simple approach to solve the giv
4 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 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
Find a pair with difference between Values and Indices in the Array
Given three integers N, V, I and an integer array nums[], find if there exists a pair of indices i, j (i < j) such that (j - i) <= I and abs(arr[j] - arr[i]) <= V. Print "Yes" if such a pair exists, else print "No". Examples: Input:N = 6, V = 2, I = 1, nums = [4, 7, 3, 2, 9, 1]Output: YesExplanation: In the given array pair index (2,3) has
4 min read
Co-prime pair with given sum minimum difference
Co-prime or mutually prime pairs are those pairs of numbers whose GCD is 1. Given a number n represent the number as the sum of a Co-prime pair (A, B) such that A - B is minimum. Examples : Input : 12 Output : 5 7 Possible co-prime pairs are (5, 7), (1, 11) but difference between 5 and 7 is minimum Input : 13 Output : 6 7 Possible co-prime pairs ar
5 min read
Pair of prime numbers with a given sum and minimum absolute difference
Given an integer 'sum' (less than 10^8), the task is to find a pair of prime numbers whose sum is equal to the given 'sum' Out of all the possible pairs, the absolute difference between the chosen pair must be minimum. If the ‘sum’ cannot be represented as a sum of two prime numbers then print “Cannot be represented as sum of two primes”.Examples:
8 min read
Check if a pair with given absolute difference exists in a Matrix
Given an N×M matrix and a difference K. The task is to check if a pair with the given absolute difference exists in the matrix or not. Examples: Input: mat[N][M] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 100}}; K = 85 Output: YES Input: mat[N][M] = {{1, 2, 3, 4}, {5, 6, 7, 8}}; K = 150 Output: NO Approach: Initialize a hash-map t
6 min read
Pair of fibonacci numbers with a given sum and minimum absolute difference
Given an integer N(less than 10^6), the task is to find a pair of Fibonacci numbers whose sum is equal to the given N, and the absolute difference between the chosen pair is minimum. Print -1 if there is no solution. Examples: Input: N = 199 Output: 55 144 Explanation 199 can be represented as sum 55 and 144 which has the minimum difference. Input:
8 min read
Product of absolute difference of every pair in given Array
Given an array arr[] of N elements, the task is to find the product of absolute differences of all pairs in the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 12Explanation: Product of |2-1| * |3-1| * |4-1| * |3-2| * |4-2| * |4-3| = 12Input: arr[] = {1, 8, 9, 15, 16} Output: 27659520 Approach: The idea is to generate every possible pair
4 min read
Maximize the minimum difference between any element pair by selecting K elements from given Array
Given an array of N integers the task is to select K elements out of these N elements in such a way that the minimum difference between each of the K numbers is the Largest. Return the largest minimum difference after choosing any K elements. Examples: Input: N = 4, K = 3, arr = [2, 6, 2, 5]Output: 1Explanation: 3 elements out of 4 elements are to
11 min read
Maximize difference between pair of nodes in a given rooted tree such that one node is ancestor of another
Given a Generic Tree consisting of N nodes valued from 0 to (N - 1) where P[i]th in the array P[] denotes ith nodes parent(1-based indexing). Each ith node has a weight attached to it, given in the array W[]. The task is to find a pair of nodes (u, v), such that u is an ancestor of v, and Wu - Wv is maximized. Note: In the array P[], -1 denotes the
14 min read
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4, 5), (5, 4)] We have existing solution for this pr
2 min read
Find any pair with given GCD and LCM
Given gcd G and lcm L. The task is to print any pair which has gcd G and lcm L.Examples: Input: G = 3, L = 12 Output: 3, 12 Input: G = 1, L = 10 Output: 1, 10 A normal solution will be to perform iteration over all the factor pairs of g*l and check if any pair has gcd g and lcm as l. If they have, then the pair will be the answer.Below is the imple
8 min read
Find a pair from the given array with maximum nCr value
Given an array arr[] of n positive integers. The task is to find elements arr[i] and arr[j] from the array such that arr[i]Carr[j] is maximum possible. In case of more than 1 valid pairs, print any one of them.Examples: Input: arr[] = {3, 1, 2} Output: 3 2 3C1 = 3 3C2 = 3 2C1 = 2 (3, 1) and (3, 2) are the only pairs with maximum nCr.Input: arr[] =
14 min read
Find the number of pair of Ideal nodes in a given tree
Given a tree of N nodes and an integer K, each node is numbered between 1 and N. The task is to find the number of pairs of ideal nodes in a tree. A pair of nodes (a, b) is called ideal if a is an ancestor of b.And, abs(a - b) ? K Examples: Input:K = 2 Output: 4 (1, 2), (1, 3), (3, 4), (3, 5) are such pairs. Input: Consider the graph in example 1 a
10 min read
Find the Mid-Alphabet for each index of the given Pair of Strings
Given two same-length strings str1 and str2 consisting of lowercase English alphabets, the task is to find the Mid-Alphabet for each index of the given pair of Strings. Examples: Input: str1 = "abcd", str2 = "cdef" Output: bcde Explanation: b is mid of a and c c is mid of b and d d is mid of c and e e is mid of e and f Input: str1 = "akzbqzgw", str
4 min read
Article Tags :
Practice Tags :