[Hacker Rank] Bear and Steady Gene

Bear and Steady Gene

  • Time : O(n)
  • Space : O(1)
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
36
bool qualify(vector<int>& freq, vector<int>& A) {
for(int i = 0; i < 4; i++) {
if(A[i] and freq[i] < A[i]) return false;
}
return true;
}

int steadyGene(string gene) {
vector<int> A(4, 0);
auto mapping = [](char& ch) {
if(ch == 'C') return 0;
if(ch == 'G') return 1;
if(ch == 'A') return 2;
return 3;
};
for(auto& ch : gene) {
A[mapping(ch)]++;
}
int n = gene.length(), stable = n / 4;
for(auto& f : A) f = max(0, f - stable);
if(!accumulate(begin(A), end(A), 0)) return 0;
vector<int> freq(4, 0);
int l = 0, r = 0, res = n;

while(r < n) {
while(r < n and !qualify(freq, A)) {
freq[mapping(gene[r++])]++;
}
while(l < r and qualify(freq, A)) {
res = min(res, r - l);
freq[mapping(gene[l++])]--;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/07/PS/HackerRank/bear-and-steady-gene/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.