You are not logged in. Please login at to post your questions!


SCHEDULE - Editorial




Author: Hasan Jaddouh
Testers: Sergey Kulik, Kamil Dębowski
Editorialist: Pawel Kacprzak




Binary search


For a binary string $A$, let's define a block as a substring of $A$ containing either only $1$'s or only $0$'s, so $111$ and $0$ are blocks, while $10$ and $0010$ are not. Moreover, let a major block be a block of $A$, such that no block in $A$ is longer that it and $L$ be the length of a major block of $A$. Notice that there can be many major blocks, but all of them have the same length.

Then the problem can be reformulated as follow: for a given binary string $A$ of length $N$ and integer $K$, we have to return the minimum $L$ (the length of a major block) that we can get by performing at most $K$ bit flips on $A$.

For example, if $A = 11100$ and $K=1$, the best we can do is to either flip the first or the second bit to get for respectively $01100$ and $10100$. In both these strings, $L$ is $2$, which is the best we can get in this case.


First, check if getting $L=1$ is possible. If yes the problem is solved, otherwise, perform a binary search on the result checking if getting $L=M$ is possible in linear time.


First of all, let's take a closer look at the constraints. It is said that $K \leq 10^6$, but since also $N \leq 10^6$ and there is no point of flipping a single bit more than once, we can rewrite the constraint as $K \leq N$.

Subtask 1

In the first subtask $N \leq 10$, so one can generate all possible strings we can get by performing at most $K$ flips on $A$, and compute the smallest $L$ among them. This is possible because there are at most $2^N$ such strings and computing $L$ for a single string takes $O(N)$ time. Thus the overall time complexity of solving all test cases will be $O(T \cdot 2^N \cdot N)$, which is completely fine for these constraints and $T \leq 11000$.

Subtask 2

In the second subtask we have $N \le 10^6$, so the problem has to be solved in a clever way. The crucial observation is that for any $L$ and any block of $A$ with length $M$, $\lceil M / (L+1) \rceil$ flips are necessary to convert that block into a substring without blocks of length greater than $L$, and we can perform exactly that many flips to do that.

For example, if we have a block of length $5$, $00000$, and $L=2$, we flip its bits with indices $L+1, 2 \cdot (L+1), 3 \cdot (L+1) \ldots$, so in this particular case, we flip only its third bit to get $00100$. Similarly, if we have a block of length $6$, $000000$, and $L=2$, we flip its third and sixth bits to get $001001$.

Thus it looks like we can perform a binary search for the answer and for a fixed $M$, check if we can transform all the blocks in $A$ into block of length at most $X$ using at most $K$ flips by just iterating over all blocks in $A$ and computing the sum of needed swaps for all of these blocks. Notice that binary search is correct here, because if it is not possible to use at most $K$ swaps to get $A$ with $L=X$, then it is also not possible to use at most $K$ swaps to get $A$ with $L \lt X$. This will result in $O(N \cdot \log N)$ time complexity for a single test case, but since the sum of $N$ across all test cases is at most $10^6$, this will run fast enough. However, we are not finished yet, because there is a tricky case to handle.

Notice that when we divide $A$ into blocks, the blocks alternate in such a way that after a block consisting of $0$'s there is a block consisting of $1$'s, then one consisting of $0$'s again and so on. The observation we made says that for a block of length $M$, $\lceil M / (L+1) \rceil$ flips are necessary and sufficient to convert this block into blocks of sizes at most $L$. It is true for an isolated block, however, since in some cases we are forced to flip the first or the last bit of such block, that may ruin our solution because that bit can create another block with adjacent blocks.

Let's take a closer look where this situation can happen, so in what cases we are really forced to flip either the first of the last bit of a block? As mentioned above, for a block of length $M$ and a fixed $L$, we can flip bits with indices $L+1, 2 \cdot (L+1), 3 \cdot (L+1) \ldots$. It follows that we are flipping its last bit if $M \mod (L+1) = 0$. However, if this happens and $L \gt 1$, we can always flip bits with indices $L, 2 \cdot L, 3 \cdot L, \ldots$ and we avoid flipping the first and the last bits, which caused the problem. But what happens when $L = 1$? Well, then we cannot use that trick, however, this case is easy to handle: at the beginning, we can just check if $A$ can be transformed using at most $K$ flips to get $L=1$. Notice that there are just $2$ possible strings of given length with $L=1$, either a sequence of alternating $0$'s and $1$'s starting with $0$ or the same but starting with $1$. If this is the case we are done. Otherwise, we use binary search described above searching for the answer in a range $[2, N]$. For implementation details, please refer to multiple solutions linked below.


Setter's solution can be found here.
First tester's solution can be found here.
Second tester's solution can be found here.
Editorialist's solution can be found here.

This question is marked "community wiki".

asked 10 Mar '17, 06:51

pkacprzak's gravatar image

5★pkacprzak ♦♦
accept rate: 12%

edited 13 Mar '17, 18:50



It's practically the same almost.

(14 Mar '17, 03:58) saikat774★

Thanks, @saikat77. The editorial of DEVSTR is quite easy to understand.

(18 Mar '17, 23:39) pratik_gadhiya3★

1234next »

This question can also be solved very easily by priority queue. First lets calculate all the lengths of consecutive 1s and 0s.Lets now make a priority queue of pair of pairs. priority_queue<pair<long,pair<long,long> > > pqueue;

Now we need to insert the (value of length,(some big number, initial value)); some big number can be 100000 for instance. Now we just need to pop from the priority queue and decrement the big number and divide the initial value by the (big number- new big number+1) and insert in the priority queue (new value,(new big number,initial value)). when break the loop.

Solve for the answer 1 separately. Here is the code snap:

while(k--) {

        long currtop=;
        long trueval= val[ix];
        long id=;
        long im=100000-id;
        currtop= trueval/(im+1);

And here is the AC code:


answered 13 Mar '17, 16:38

abx_2109's gravatar image

accept rate: 0%

can you explain how and why it works?What is the use of big number

(13 Mar '17, 18:37) nil962★

it is simple greedy technique.The longest segment stays on the top of the priority queue, we pop it and divide it by the required factor.Now purpose of a big number is when the top and the second element of the queue are the same i.e suppose we have 4,4.Now we wish to pop that element first which has been divided by a lesser factor.Hence initially we select a big number in the priority queue.

(13 Mar '17, 22:16) abx_21095★

Really nice way to solve this. Thanks for sharing your method. And using "trueval" and "id" is really good. :D

(14 Mar '17, 06:45) chandyshot4★

@saurabh9456 .. that won't work.. consider the string "111111111" and K=2 .. the optimal answer is 3 and with ur algorithm the answer would be 4.


answered 13 Mar '17, 16:14

kmalhotra30's gravatar image

accept rate: 0%

It's nice to editorials too early.


answered 13 Mar '17, 16:32

chandyshot's gravatar image

accept rate: 17%

Alternative Solution: Maintain a set of all original segments.Think of 'k' as total resources you have to allot to these segments to minimise the maximum contigous same bits.One can calculate the closed form for maximum subsegment size of the original segment when 'x' resources are alloted to the segment.The first element always corresponds to the original segment having maximum sub-segment size.At each iteration we allot one more resources to the first segment and calculate its new position in the set.The procedure terminates when k=0 . Complexity : O(n*logn)


answered 13 Mar '17, 18:05

ps_1234's gravatar image

accept rate: 0%

@shibli786 Binary search is used to reduce the computation effort.If we know that a may be the possible answer then there is no use in checking for the numbers > a else check for the numbers < a . If a doesn't satisfy then check for the numbers>a till u find a minimum value that satisfy it.


answered 14 Mar '17, 13:09

daljit1's gravatar image

accept rate: 0%

edited 14 Mar '17, 13:12

and how we will know about a ?

(14 Mar '17, 15:38) shibli7862★

one can start with a equal to the size of the maximum consecutive block in the initial given string since our answer has to be less than or equal to it .

(14 Mar '17, 18:13) daljit12★

best editorial


answered 03 Apr '17, 23:29

coder_ishmeet's gravatar image

accept rate: 0%

I had an algorithm to solve it by storing segments in heap, and dividing longest segment by two and storing both parts again in heap. Will it work? Is there a easy way to check if it is possible to make answer 1. If it does suggest.


answered 13 Mar '17, 16:09

saurabh9456's gravatar image

accept rate: 0%

Make two strings str0 and str1 that are alternating 0's and 1's, str0 starts with 0 and str1 starts with 1. Now let cnt0 and cnt1. start comparing your input string str with str0. if str[i] != str0[1] cnt0++; similarly compare str and str1 and get cnt1; Now in variables cnt0 and cnt1 you actually have number of flips required to make string str alternating 0's and 1's starting with 0 or 1 respectively. Now if(k >= min(cnt0, cnt1)) then for sure you can make alternating string. thus in this case answer is 1.

(14 Mar '17, 06:55) chandyshot4★

@kmalhotra30 Thank you :) after two flips string will be something like 110111011.


answered 13 Mar '17, 16:34

siddharthp538's gravatar image

accept rate: 11%

edited 13 Mar '17, 16:35

I am getting NZEC error in this code. can anyone explain why i am getting this error?


answered 13 Mar '17, 16:54

rishabh245's gravatar image

accept rate: 0%

My code is working in 3/9 case can someone help me with this . code link->


answered 13 Mar '17, 17:03

ajaman13's gravatar image

accept rate: 0%

no code there...

(14 Mar '17, 09:57) rcsldav20175★
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 10 Mar '17, 06:51

question was seen: 6,260 times

last updated: 10 Mar, 16:58