Maximum Odd Binary Number — LeetCode 2864 Python Solution
- Problem
- #2864
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
class Solution:
def maximumOddBinaryNumber(self, s: str) -> str:
cnt = s.count("1")
return "1" * (cnt - 1) + (len(s) - cnt) * "0" + "1"Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.