Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
593 views
in Online Assessments by Expert (46,090 points) | 593 views

2 Answers

0 like 0 dislike
Best answer
1st question:
input string contains 'a' and 'b'. blocks are defined as contiguos elements which have same alphabets. eg, i/p babaa has 4 blocks b, a, b, aa.
number of inserts required to make all blocks of equal length.
by Expert (46,090 points)
0 like 0 dislike
public int solution(String S) {
       char[] myArray = S.toCharArray();
       List<Integer> blockInfo = new ArrayList<>();
       char previous = myArray[0];
       int previousLength  =1;
       int length = myArray.length;
       for(int i=1; i<length; i++){
           if(myArray[i] == previous){
               previousLength++;
           } else {
               blockInfo.add(previousLength);
               previous = myArray[i];
               previousLength = 1;
           }
       }
       blockInfo.add(previousLength);

       int max = blockInfo.get(0);
       for(int i=0; i<blockInfo.size(); i++){
           if(max < blockInfo.get(i)){
               max = blockInfo.get(i);
           }
       }
       int count = 0 ;
       for(int i=0; i< blockInfo.size(); i++){
           count += (max - blockInfo.get(i));
       }

       return count;

   }
by Expert (46,090 points)