Maximum Odd Binary Number — LeetCode 2864 Python Solution

EasyGreedyMathString
Problem
#2864
Pattern
Greedy
Reading time
2 min

The problem

You are given a binary string s that contains at least one '1'. You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.

Example

Input
s = "010"
Output
"001"
Explanation
Because there is just one '1', it must be in the last position. So the answer is "001".

Python solution

Python
class Solution:
    def maximumOddBinaryNumber(self, s: str) -> str:
        cnt = s.count("1")
        return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1"

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2864. Maximum Odd Binary Number 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

Frequently asked questions

How hard is LeetCode 2864. Maximum Odd Binary Number?
LeetCode 2864. Maximum Odd Binary Number is rated Easy on LeetCode.
What is the time complexity of LeetCode 2864. Maximum Odd Binary Number?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2864. Maximum Odd Binary Number?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2864. Maximum Odd Binary Number cover?
LeetCode 2864. Maximum Odd Binary Number is tagged Greedy, Math 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.

Get Stealth Interview