Maximum Odd Binary Number - Problem

Imagine you have a collection of binary digits (0s and 1s) that form a binary string, and you want to create the largest possible odd binary number by rearranging these digits.

Given a binary string s that contains at least one '1', your task is to rearrange the bits to form the maximum odd binary number possible.

Key Points:

  • A binary number is odd if and only if its last digit is '1'
  • To maximize the value, we want as many '1's as possible in the most significant positions
  • The result can have leading zeros (they don't affect the value)

Example: If you have "0011", you can rearrange it to "1101" which is the maximum odd number possible.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "010"
โ€บ Output: "101"
๐Ÿ’ก Note: We have one '1' and two '0's. To make the maximum odd number, we place the '1' at the front and keep one '1' at the end. Since we only have one '1' total, it must go at the end, giving us "101".
example_2.py โ€” Multiple 1s
$ Input: s = "0101"
โ€บ Output: "1001"
๐Ÿ’ก Note: We have two '1's and two '0's. We place (2-1)=1 '1' at the front, then all '0's in the middle, and finally one '1' at the end: '1' + '00' + '1' = "1001".
example_3.py โ€” All 1s
$ Input: s = "111"
โ€บ Output: "111"
๐Ÿ’ก Note: When all characters are '1', we place (3-1)=2 '1's at the front and one '1' at the end. Since there are no '0's, the result is "111".

Constraints

  • 1 โ‰ค s.length โ‰ค 100
  • s consists only of '0' and '1'
  • s contains at least one '1'

Visualization

Tap to expand
Maximum Odd Binary Number StrategyExample: s = "001101"Input Analysis:001101Count: 3 ones, 3 zerosStep 1: Reserve 1 for end (oddness)1Reserved for last positionStep 2: Place remaining 1s at front11(ones - 1) = 2 ones at frontStep 3: Fill middle with all 0s11000All 3 zerosStep 4: Add reserved 1 at end110001Ensures oddnessFinal Result: "110001"Binary value: 110001โ‚‚ = 49โ‚โ‚€ (maximum possible odd number)
Understanding the Visualization
1
Count Your Resources
Count how many 1s (valuable) and 0s (fillers) you have
2
Maximize Front Value
Place as many 1s as possible at the front for maximum value
3
Save One 1 for End
Reserve exactly one 1 for the last position to ensure oddness
4
Fill Middle with 0s
Place all 0s between the front 1s and the last 1
Key Takeaway
๐ŸŽฏ Key Insight: To maximize an odd binary number, place all 1's except one at the front for maximum value, and exactly one 1 at the end for oddness.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
28.0K Views
Medium Frequency
~8 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen