[Hacker Rank] Pairs

Pairs

  • Two Pointer Solution
  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
int pairs(int k, vector<int> A) {
sort(begin(A), end(A));
int res = 0, n = A.size(), l = 0, r = 0;

while(r < n) {
while(r < n and A[l]*1ll + k > A[r]) r++;
if(A[l]*1ll + k == A[r]) {
res++; l++, r++;
} else l++;
}

return res;
}
  • Hash Table Solution
  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
int pairs(long k, vector<int> A) {
unordered_set<long> us;
int res = 0;
for(auto& a : A) {
if(us.count(a-k)) res++;
if(us.count(a+k)) res++;
us.insert(a);
}

return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/13/PS/HackerRank/pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.