DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

Making a Monochrome String

Back to problem

Editorial

Let C0C_0C0​ and C1C_1C1​ be the number of 0\texttt{0}0s and 1\texttt{1}1s, respectively.

If C0=0C_0=0C0​=0 or C1=0C_1=0C1​=0, the string is already monochrome, so the answer is 00.

If C0=C1C_0=C_1C0​=C1​, we can delete the whole string in one operation, so the answer is 111.

Now assume C0≠C1C_0 \ne C_1C0​=C1​ and both characters exist. Let the more frequent character be the majority character. Convert the majority character to +1+1 and the other character to . Let the resulting array be , and let its total sum be . Then .

A deletable substring is exactly a substring with sum 000. Therefore, no sequence of operations changes the total sum DDD. Since the final string must be monochrome, it must consist of exactly DDD majority characters.

Thus, the problem becomes the following.

Keep some majority characters and divide all other characters into contiguous zero-sum segments. Minimize the number of deleted segments.

Define prefix sums as follows.

P0=0,Pi=A1+A2+⋯+AiP_0 = 0,\qquad P_i = A_1 + A_2 + \cdots + A_iP0​=0,Pi​=A
0
+
1
−1-1−1
AAA
DDD
D>0D>0D>0
1​
+
A2​+
⋯+
Ai​

A segment (l+1,…,r)(l+1,\ldots,r)(l+1,…,r) has sum 000 if and only if Pl=PrP_l=P_rPl​=Pr​.

Let dpidp_idpi​ be the minimum number of operations needed after processing the first iii characters, where position iii is the current boundary. If the character at position j+1j+1j+1 is a majority character, we may keep it. Before keeping it, we may delete the segment from a previous boundary iii to position jjj, but only when Pi=PjP_i=P_jPi​=Pj​.

Maintain best[x]best[x]best[x], the minimum dpdpdp value among previous boundaries with prefix sum xxx. Then each transition can be processed in O(1)O(1)O(1).

The total time complexity is O(N)O(N)O(N), and the memory complexity is O(N)O(N)O(N).