Magicsheet logo

Maximum Odd Binary Number

Easy
12.5%
Updated 8/1/2025

Maximum Odd Binary Number

What is this problem about?

The Maximum Odd Binary Number coding problem gives you a binary string s (containing only '0's and '1's). You need to rearrange the characters of s to form the largest possible odd binary number. An odd binary number is one whose last bit (rightmost bit) is '1'.

Why is this asked in interviews?

Microsoft, Meta, Amazon, Google, and Bloomberg use this as an easy problem to test fundamental string manipulation, greedy choices, and understanding of binary representation. It's designed to quickly assess if a candidate can identify the simple greedy strategy for constructing the largest odd binary number.

Algorithmic pattern used

Greedy Approach: To form the largest possible binary number, we want to place as many '1's as possible to the left (most significant bits). To make the number odd, the very last bit (least significant bit) must be '1'.

The greedy strategy is:

  1. Count the number of '1's in the input binary string s.
  2. Place all but one '1' at the beginning of the new string.
  3. Place all '0's after these leading '1's.
  4. Place the remaining single '1' at the very end.

This ensures:

  • The number is odd (ends with '1').
  • It's maximized because all available '1's (which contribute more value than '0's) are placed as far left as possible, subject to the odd number constraint.

Example explanation

s = "0101"

  1. Count '1's: 2.
  2. Place all but one '1' at the beginning: s becomes "1".
  3. Place all '0's: s becomes "100". (There are two '0's).
  4. Place the remaining single '1' at the very end: s becomes "1001".

Result: "1001". (Binary "1001" is decimal 9, which is the largest odd number you can make from "0101").

s = "001"

  1. Count '1's: 1.
  2. Place all but one '1' at the beginning: (no '1's left to place here).
  3. Place all '0's: s becomes "00".
  4. Place the remaining single '1' at the very end: s becomes "001".

Result: "001". (Decimal 1).

Common mistakes candidates make

  • Not understanding binary oddness: Forgetting that an odd binary number must end in '1'.
  • Incorrect placement of digits: Trying to place '0's strategically when they should primarily fill space after the leading '1's.
  • Handling strings with no '1's: If s contains no '1's, it's impossible to form an odd number. The problem context usually implies at least one '1' will be present, or an empty string for the odd number would be the result.

Interview preparation tip

For the Math String Greedy interview pattern, this problem is a clear example of how a simple greedy strategy can optimally solve construction problems when the rules are well-defined. Focus on breaking down the constraints and identifying the most impactful placements of digits.

Similar Questions