Find a pair with the given difference in C++


Consider we have an array A, there are n different elements. We have to find a pair (x, y) from the array A, such that the difference between x and y is same as given difference d. Suppose a list of elements are like A = [10, 15, 26, 30, 40, 70], and given difference is 30, then the pair will be (10, 40) and (30, 70)

To solve this problem, we will assume that the array is sorted, then starting from left we will take two pointers to point elements, initially first one ‘i’ will point to the first element, and second one ‘j’ will point to the second element. when A[j] – A[i] is same as n, then print pair, if A[j] – A[i] < n, then increase j by 1, otherwise increase i by 1.

Example

 Live Demo

#include<iostream>
using namespace std;
void displayPair(int arr[], int size, int n) {
   int i = 0;
   int j = 1;
   while (i < size && j < size) {
      if (i != j && arr[j] - arr[i] == n) {
         cout << "(" << arr[i] << ", " << arr[j] << ")"<<endl;
         i++; j++;
      }
      else if (arr[j]-arr[i] < n)
         j++;
      else
         i++;
   }
}
int main() {
   int arr[] = {10, 15, 26, 30, 40, 70};
   int size = sizeof(arr)/sizeof(arr[0]);
   int n = 30;
   displayPair(arr, size, n);
}

Output

(10, 40)
(40, 70)

Updated on: 24-Oct-2019

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements