[InterviewBit] Two out of Three

Two out of Three

  • 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
31
32
33
34
35
vector<int> Solution::solve(vector<int> &A, vector<int> &B, vector<int> &C) {
sort(begin(A), end(A));
sort(begin(B), end(B));
sort(begin(C), end(C));
int a = 0, b = 0, c = 0;
int n = A.size(), m = B.size(), k = C.size();
vector<int> res;
while(a < n or b < m or c < k) {
int mi = INT_MAX;
if(a < n) mi = min(A[a], mi);
if(b < m) mi = min(B[b], mi);
if(c < k) mi = min(C[c], mi);
if(mi == -1) break;
if(a < n and b < m and A[a] == B[b] and A[a] == mi) {
res.push_back(A[a]);
a += 1;
b += 1;
} else if(a < n and c < k and A[a] == C[c] and A[a] == mi) {
res.push_back(A[a]);
a += 1;
c += 1;
} else if(b < m and c < k and B[b] == C[c] and B[b] == mi) {
res.push_back(B[b]);
b += 1;
c += 1;
} else {
if(a < n and A[a] == mi) a += 1;
if(b < m and B[b] == mi) b += 1;
if(c < k and C[c] == mi) c += 1;
}
}
res.erase(unique(begin(res),end(res)), end(res));
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/04/PS/interviewbit/two-out-of-three/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.