Maximum Odd Binary Number - 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.

Return a string representing the maximum odd binary number that can be created from the given combination.

Note that the resulting string can have leading zeros.

Input & Output

Example 1 — Basic Case
$ Input: s = "010"
Output: "001"
💡 Note: We have one '1' and two '0s. To maximize and keep odd: place 0 '1's at front (since 1-1=0), two '0's in middle, and one '1' at end → "001"
Example 2 — Multiple 1s
$ Input: s = "101"
Output: "101"
💡 Note: We have two '1's and one '0'. Place 1 '1' at front, one '0' in middle, one '1' at end → "101". This is already optimal.
Example 3 — Many 1s
$ Input: s = "1111"
Output: "1111"
💡 Note: All bits are '1'. Place 3 '1's at front, no '0's in middle, one '1' at end → "1111". Already maximum odd number.

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 INPUT Binary String s = "010" 0 idx 0 1 idx 1 0 idx 2 Bit Count: Count of '1': 1 Count of '0': 2 Goal: Create max odd number Input: s = "010" ALGORITHM STEPS 1 Count Bits ones=1, zeros=2 2 Reserve One '1' Keep 1 for last position 3 Place Remaining 1s At front (ones-1 = 0) 4 Place All 0s In middle (zeros = 2) Construction: (ones-1) x '1' = "" zeros x '0' = "00" + '1' at end = "001" Result: "" + "00" + "1" FINAL RESULT Rearranged Binary: 0 pos 0 0 pos 1 1 LSB Why "001"? - '1' at end makes it odd - No extra 1s to place - Decimal value: 1 Verification: OK 001 is odd (ends in 1) Output: "001" Key Insight: For a binary number to be odd, its LSB (rightmost bit) must be '1'. To maximize the value, place all remaining '1's at the leftmost positions, then all '0's, then exactly one '1' at the end. TutorialsPoint - Maximum Odd Binary Number | Greedy Construction
Asked in
Google 25 Amazon 20 Microsoft 15
32.0K Views
Medium Frequency
~15 min Avg. Time
850 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