Maximum Binary String After Change - Problem

You are given a binary string binary consisting of only 0's and 1's. You can apply each of the following operations any number of times:

Operation 1: If the string contains the substring "00", you can replace it with "10".
For example, "00010""10010"

Operation 2: If the string contains the substring "10", you can replace it with "01".
For example, "00010""00001"

Return the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.

Input & Output

Example 1 — Basic Case
$ Input: binary = "000110"
Output: "111011"
💡 Note: Apply operations: 000110 → 100110 → 110110 → 111010 → 111001. No more beneficial operations possible.
Example 2 — Single Zero
$ Input: binary = "01"
Output: "10"
💡 Note: Direct application of Operation 2: 01 becomes 10 using the 10→01 rule in reverse.
Example 3 — No Zeros
$ Input: binary = "111"
Output: "111"
💡 Note: String contains no zeros, so no operations can be applied. Return unchanged.

Constraints

  • 1 ≤ binary.length ≤ 105
  • binary consists of only '0' and '1'

Visualization

Tap to expand
Maximum Binary String After Change INPUT Binary String: "000110" 0 [0] 0 [1] 0 [2] 1 [3] 1 [4] 0 [5] Operation 1: "00" --> "10" (increase value) Operation 2: "10" --> "01" (move 0 right) Goal: Maximize binary value (More 1s at left = larger) ALGORITHM STEPS 1 Find First Zero Skip leading 1s, find first 0 000110: pos = 0 2 Count Zeros Count all 0s after first zero zeros = 4 (positions 0,1,2,5) 3 Move All 0s Right Use Op2 to push 0s rightward 000110 --> 000011 4 Convert 00 to 10 Apply Op1 to consecutive 0s 000011 --> 111011 Pattern Recognition: Result = 1s + single 0 + remaining 1s 111...1 0 1...1 Zero at position: first_zero + zeros - 1 FINAL RESULT Maximum Binary String: 1 1 1 0 1 1 Output: "111011" Transformation Trace: 000110 (input) 000101 (Op2: move 0) 000011 (Op2: move 0) 100011 (Op1: 00-->10) 111011 (final) [OK] Maximum achieved! Key Insight: The greedy pattern: All zeros (except possibly one) can be converted to 1s. Using Op2, we can collect all zeros together, then use Op1 to convert "00" to "10" repeatedly. The final string has exactly ONE zero at position (first_zero_pos + total_zeros - 1), with all other positions being 1. TutorialsPoint - Maximum Binary String After Change | Greedy - Pattern Recognition
Asked in
Google 15 Facebook 12
30.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen