
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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)
Advertisements