We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I find the optimal length of the substring to be replaced using binary search and for a given substring length I swipe through all possible substrings. The length of the substring to be replaced must be larger than the number of letters which I need to add to the rest of the string to compensate for the unequal number of letters in the latter.
The solution scales as N*log(N)
constintN_letters=4;intmy_map(charc){if(c=='A')return0;if(c=='C')return1;if(c=='T')return2;if(c=='G')return3;return-1;}// Obtain array with the number of each kind of letters in the stringarray<int,N_letters>Get_letters_count(stringgene){array<int,N_letters>arr={};for(charc:gene){arr[my_map(c)]++;}returnarr;}// How many letters need to be replaced from looking at the rest of the stringintGet_num_of_letters_to_replace(array<int,N_letters>letters_count){intans=0;intmax_lett=*max_element(letters_count.begin(),letters_count.end());for(autoa:letters_count){ans+=max_lett-a;}returnans;}/////////////////////////////////////////////////////////intsteadyGene(stringgene){intN=gene.length();array<int,N_letters>letters_count=Get_letters_count(gene);intlett_to_replace=Get_num_of_letters_to_replace(letters_count);if(lett_to_replace==0)return0;// Start binary search (analogous to bisection method)intans=N;intl_min=0;intl_max=N;intl=int(N/2);while(l>=1){// Look at the substring of length l starting at the beginning of the genestrings1="";strings2=gene.substr(l,N-l);letters_count=Get_letters_count(s2);lett_to_replace=Get_num_of_letters_to_replace(letters_count);for(inti=0;i<N-l;i++){// Shift the substring by 1 element and update itif(i>0){letters_count[my_map(gene[i-1])]++;letters_count[my_map(gene[i+l-1])]--;lett_to_replace=Get_num_of_letters_to_replace(letters_count);}// If I found the solution for the string of length l then try the solution for a shorter lengthif(l>=lett_to_replace){ans=l;break;}}if(ans==l){l_max=l;l=int((l_min+l_max)/2);}// If I did not find a solution of length l, try longer substringelse{l_min=l;l=int(l_min+l_max)/2;}if(l_max-l_min<=1)break;}returnans;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Bear and Steady Gene
You are viewing a single comment's thread. Return to all comments →
I find the optimal length of the substring to be replaced using binary search and for a given substring length I swipe through all possible substrings. The length of the substring to be replaced must be larger than the number of letters which I need to add to the rest of the string to compensate for the unequal number of letters in the latter. The solution scales as N*log(N)