Maximum Binary String After Change Problem
Description
LeetCode Problem 1702.
You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times:
- Operation 1: If the number contains the substring
"00", you can replace it with"10".- For example,
"00010" -> "10010"
- For example,
- Operation 2: If the number contains the substring
"10", you can replace it with"01".- For example,
"00010" -> "00001"
- For example,
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.
Example 1:
Input: binary = "000110"
Output: "111011"
Explanation: A valid transformation sequence can be:
"000110" -> "000101"
"000101" -> "100101"
"100101" -> "110101"
"110101" -> "110011"
"110011" -> "111011"
Example 2:
Input: binary = "01"
Output: "01"
Explanation: "01" cannot be transformed any further.
Constraints:
1 <= binary.length <= 10^5binaryconsist of'0'and'1'.
Solution
Approach: Observation
Operation 2 lets any 1 slide to the right past a 0, so every 1 that comes after the first 0 can be pushed to the end of the string. Operation 1 then turns a run of zeros 00...0 into 11...10.
So the best we can do is: keep the leading 1s, gather all remaining zeros into one block right after them, and turn that block into 1s followed by a single 0. The result has at most one 0.
If the string has no 0, return it as is. Otherwise let k be the index of the first 0. The final 0 sits at k plus the number of zeros after position k; every other position is 1.
Complexity: O(n) time and O(n) space for the result, where n is the length of the string.
class Solution:
def maximumBinaryString(self, binary: str) -> str:
k = binary.find('0')
if k == -1:
return binary
k += binary[k + 1 :].count('0')
return '1' * k + '0' + '1' * (len(binary) - k - 1)