[InterviewBit] 4 Sum

4 Sum

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
vector<vector<int>> Solution::fourSum(vector<int> &A, int B) {
vector<vector<int>> res;
sort(begin(A), end(A));
int n = A.size();
for(int i = 0; i < n - 3; i++) {
if(i and A[i] == A[i-1]) continue;
if(A[i] + A[i + 1] + A[i + 2] + A[i + 3] > B) break;
if(A[i] + A[n - 1] + A[n - 2] + A[n - 3] < B) continue;
for(int j = i + 1; j < n - 2; j++) {
if(j > i + 1 and A[j] == A[j-1]) continue;
if(A[i] + A[j] + A[j + 1] + A[j + 2] > B) break;
if(A[i] + A[j] + A[n - 1] + A[n - 2] < B) continue;
int l = j + 1, r = n - 1;
while(l < r) {
int now = A[i] + A[j] + A[l] + A[r];
if(now < B) l++;
else if(now > B) r--;
else {
res.push_back({A[i], A[j], A[l], A[r]});
int left = A[l], right = A[r];
if(left == right) break;
while(l < r and A[l] == left) l++;
while(l < r and A[r] == right) r--;
}
}
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/24/PS/interviewbit/4-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.