MediumNo. 1702

Maximum Binary String After Change — LeetCode 1702 Python Solution

Pattern
Greedy
Topics
Greedy, String
Reading time
2 min

The problem

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".

Example

Input
binary = "000110"
Output
"111011"
Explanation
A valid transformation sequence can be:

Python solution

PythonSolution
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)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1702. Maximum Binary String After Change is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0179Largest NumberMedium
0316Remove Duplicate LettersMedium
0402Remove K DigitsMedium
0420Strong Password CheckerHard
0649Dota2 SenateMedium
0680Valid Palindrome IIEasy

Frequently asked questions

How hard is LeetCode 1702. Maximum Binary String After Change?

LeetCode 1702. Maximum Binary String After Change is rated Medium on LeetCode.

What is the time complexity of LeetCode 1702. Maximum Binary String After Change?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1702. Maximum Binary String After Change?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1702. Maximum Binary String After Change cover?

LeetCode 1702. Maximum Binary String After Change is tagged Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.