Binary Search, Hash, and Two-Pointer Approaches to the "A-B" Problem
Last updated on March 4, 2025 am
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
引用
Problem Description
Given a sequence of positive integers and a positive integer $C$, count the number of pairs satisfying $A - B = C$ (pairs with the same numbers at different positions count as different pairs).
Input Format
The input consists of two lines.
The first line contains two positive integers $N,C$.
The second line contains $N$ positive integers, the sequence to be processed.
Output Format
One line, representing the number of pairs satisfying $A - B = C$ contained in the sequence of positive integers.
Input/Output Sample #1
Input #1
4 1 1 1 2 3Output #1
3Notes/Hints
For $75%$ of the data, $1 \leq N \leq 2000$.
For $100%$ of the data, $1 \leq N \leq 2 \times 10^5$, $0 \leq a_i <2^{30}$, $1 \leq C < 2^{30}$.
Solutions
Binary Search Approach
Consider that the original problem asks for the number of pairs satisfying $a_i-a_j=C$. If we enumerate $a_i$, then we only need to find the count of values equal to $a_j=a_i-C$ in the original sequence.
For a sorted array, the parts with equal values necessarily form a contiguous segment. So we can use the lower_bound() and upper_bound functions to quickly find the left and right endpoints of this contiguous segment, i.e., the positions of the first and last occurrence (the one after it) of $a_i-C$ in the sequence, and then add the length of this interval.
Since lower_bound()-a.begin() and upper_bound()-a.begin() are the respective indices we want, subtracting them gives the length of the interval.
The code implementation is as follows:
代码
#include<bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
using u32=unsigned;
using u128=unsigned __int128;
int main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
int n,c;
cin>>n>>c;
vector<int> a(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a.begin(),a.end());
i64 ans=0;
for(int x:a){
ans+=upper_bound(a.begin(),a.end(),x-c)-lower_bound(a.begin(),a.end(),x-c);
}
cout<<ans;
return 0;
}Time complexity: $O(nlogn)$
Hashing Approach
Same as above, we iterate over $a_i$, and only need to find the count of $a_i-c$ in the array.
So we can first use a linear table to store the sequence itself, then use a map<int,int> to store the count corresponding to each number, and finally accumulate them one by one.
The code implementation is as follows:
代码
#include<bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
using u32=unsigned;
using u128=unsigned __int128;
const int inf=0x3f3f3f3f;
int main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
int n,c;
cin>>n>>c;
vector<int> a(n);
map<int,int> mp;
for(int i=0;i<n;i++){
cin>>a[i];
mp[a[i]]++;
}
i64 ans=0;
for(int x:a){
ans+=mp[x-c];
}
cout<<ans;
return 0;
}Since the sorting step is eliminated, the time complexity is $O(n)$, which is the optimal time complexity, because reading the input itself is already $O(n)$.
Two-Pointer Approach
Using the meaning of the lower_bound() and upper_bound() functions mentioned above, we can consider maintaining two pointers, a left pointer $left$ and a right pointer $right$.
For the sorted array vector<int> a, iterate over the array: let a[left] be the first number ≥ a[i]-c, and let a[right] be the first number > a[i]-c. This way, all numbers from a[left] to a[right] are equal to a[i]-c, so the count of numbers equal to a[i]-c is always right-left, which is added to the answer.
In this process, a[i]-c is increasing, so both $left$ and $right$ keep moving to the right.
代码
#include<bits/stdc++.h>
using namespace std;
using i64=long long;
using u64=unsigned long long;
using u32=unsigned;
using u128=unsigned __int128;
int main(){
ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
int n;
i64 c;
cin>>n>>c;
vector<i64> a(n);
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a.begin(),a.end());
i64 cnt=0;
int left=0,right=0;
for(int i=0;i<n;i++){
while(a[left]<a[i]-c) left++;
while(a[right]<=a[i]-c) right++;
if(a[i]-c==a[left]) cnt+=right-left;
}
cout<<cnt;
return 0;
}Time complexity: $O(nlogn)$, which is the complexity of sort(). After sorting, the complexity is $O(n)$, because both the left pointer and the right pointer only move from the beginning to the end.