NeetCode #765LC-2864EasyGreedy
← Back to All Problems#765 · #2864 · Maximum Odd Binary Number(最大二进制奇数)
📌 Problem Statement & Constraints
You are given a binary string
s containing at least one 1. Rearrange its bits to form the maximum odd binary number (a binary string with no leading zeros). Constraints: 1 <= s.length <= 100.💡 Core Algorithmic Approaches
- A binary number is odd iff its last bit is
1, so reserve one1for the end. - To maximise the value, place all remaining
1bits at the front (the most significant positions). - Then place all
0bits, and finish with the reserved1. - This yields the shape
1...10...01.
💻 Benchmark Python3 Implementation
class Solution:
def maximumOddBinaryNumber(self, s: str) -> str:
ones = s.count("1")
zeros = len(s) - ones
return "1" * (ones - 1) + "0" * zeros + "1"⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): counting the bits plus building the result.
💾 Space Complexity
O(n): the output string.
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the trailing
1: without it the number is even and the result is wrong. - Placing a
0at the front: the result must have no leading zeros, so the leading positions are all1. - Assuming the string already has a fixed length: the length is preserved by rearranging, and the counts add up.
- Using
ones - 1whenones == 0: the constraint guarantees at least one1, so this is safe.