Sanket and string doubt


what is the logical error in this code

Hello @chahatkumar,
In your code, as soon as the first string where count is equal to k is found, it stops checking for strings any further.
So, you need think of a logic which checks all the strings.
Also, instead of count, you will have to maintain a separate counter for a and b and check if min(count_a,count_b)<k.

okay, but how does it stops checking for other string? will the for loop not start again with increment in i value?
also i am not able to makes, can u pls make changes in my current code?

Here is the update code: https://ide.codingblocks.com/s/106498
I have used an array two store the counts of a and b. 0th index is for a and 1st index is for b.
Like if you understood.

1 Like

You can also refer to my code: https://ide.codingblocks.com/s/106500
This gives the answer in O(n).
Read both of them and go with whichever you find easier to understand.

okay thanks
but this updated code is giving wrong output :frowning_face:

It is working fine

1 Like

okay thankyou :slight_smile:

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like

sir, i do not understand line no 15
why are we taking min value and comparing to k
pls elaborate this part

Hello @chahatkumar,

We are taking minimum count to find the character(either a or b) which has occurred less no of times till that particular iteration.
Because we would change the occurrence of only that character which are in minority, to determine the , maximum value.

We are comparing the minimum value with k because we can make k changes at max.
If, the minimum count is greater than k , then it means that we cannot swap all the occurrence of the character that has lesser count.
Thus, we increment l.

For better understanding, dry run your code on ababaa, with k=1.

Hope, this would help.
Give a like, if you are satisfied.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

@D18LP0082 I have understood your implementation, but not completely, can you please explain what do these lines actually do:
if(min(count[0], count[1]) > k){
count[str[l] - ‘a’]–;
l++;
}