While loop in the function

what is the need of this
if (j < s.size() - 1 && s[i - 1] != ch)
{
j++;
}

what it does. can you explain with example ?

Hi @premang

Regarding your this code snippet, here I’m telling you this answer, considering i as left pointer and j as right pointer (if this is not the case in your code then please let me know).

So, here we are checking if character at just previous index of your left pointer was not equal to ch, then that index must be counted as a swap earlier. So, now as we are not considering that character we have a free swap available, so to use that swap we are just increasing our right pointer by 1.

For Example

Given string is
babbbb

and value of K = 1

So, indexes for given string are like
0 - a
1 - a
2 - b
3 - b
4 - a
5 - b

Now let’s say at some point,
our left-pointer(i) is at index 1 and our right-pointer(j) is at index 3
So, our substring(i to j) would look like “abb” and to make it a perfect string i.e. “bbb” we will need atleast 1 swap.

Now, let’s say if we moved ahead and
our left-pointer(i) is at index 2 and our right-pointer(j) is at index 4
So, our substring(i to j) would look like “bba”
So, now as
string [ i ] = b
string [ i - 1 ] = a

Now, you can see string [ i ] != string [ i - 1 ], so that 1 swap that we have earlier considered for index 1 to convert a to b is free now. bcz now our substring is from index 2 to 4 and that index 1 is not the part of current substring, so that 1 swap could be used now to convert ‘a’ (index - 4) to ‘b’.

I hope it helps you :slight_smile:

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.