
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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)
- Related Articles
- JavaScript Program to Find a pair with the given difference
- Find the Pair with Given Sum in a Matrix using C++
- Find a pair with given sum in BST in C++
- Find a pair with given sum in a Balanced BST in C++
- Find a pair with given sum in a Balanced BST in Java
- Find a pair from the given array with maximum nCr value in Python
- Find a pair from the given array with maximum nCr value in C++
- Find any pair with given GCD and LCM in C++
- Find pair with maximum difference in any column of a Matrix in C++
- Find Maximum difference pair in Python
- Check if a pair with given product exists in a Matrix in C++
- Find the Pair with a Maximum Sum in a Matrix using C++
- Count ways of choosing a pair with maximum difference in C++
- Find pairs with given sum such that pair elements lie in different BSTs in Python
- Check if a pair with given product exists in Linked list in C++

Advertisements