2864. Maximum Odd Binary Number - Explanation

Problem Link

Description

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.

Example 1:

Input: s = "0110"

Output: "1001"

Explanation: One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001".

Example 2:

Input: s = "100"

Output: "001"

Explanation: Because there is just one '1', it must be in the last position. So the answer is "001".

Constraints:

  • 1 <= s.length <= 100
  • s consists only of '0' and '1'.
  • s contains at least one '1'.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.



Prerequisites

Before attempting this problem, you should be comfortable with:

  • Binary Number Representation - Understanding that odd numbers must end with bit 1, and higher-order bits contribute more to value
  • String Manipulation - Converting between strings and character arrays, swapping elements
  • Greedy Algorithms - The optimal structure can be determined without exhaustive search
  • Two Pointers (optional) - An efficient in-place partitioning approach similar to quicksort's partition step

1. Sorting

Intuition

A binary number is odd if and only if its last bit is 1. To maximize the number, we want as many 1s as possible in the higher-order positions (leftmost).

We can sort the string in descending order to push all 1s to the front. Then, we swap one 1 to the last position to ensure the number is odd. Since we sorted in descending order, the rightmost 1 is easy to find.

Algorithm

  1. Convert the string to a character array and sort in descending order (all 1s come first).
  2. Find the last 1 in the sorted array (it will be at the boundary between 1s and 0s).
  3. Swap this 1 with the last character of the array.
  4. Return the resulting string.
class Solution:
    def maximumOddBinaryNumber(self, s: str) -> str:
        s = sorted(s)
        s.reverse()
        i = len(s) - 1
        while i >= 0 and s[i] == "0":
            i -= 1

        s[i], s[len(s) - 1] = s[len(s) - 1], s[i]
        return ''.join(s)

Time & Space Complexity

  • Time complexity: O(nlogn)O(n \log n)
  • Space complexity: O(n)O(n)

2. Greedy

Intuition

We do not actually need to sort. The optimal answer has a simple structure: place all but one 1 at the beginning, followed by all 0s, and end with a single 1.

We just need to count the 1s. If there are count ones, the result is (count - 1) ones, then (n - count) zeros, then one 1.

Algorithm

  1. Count the number of 1s in the string.
  2. Construct the result: (count - 1) ones + (length - count) zeros + 1.
  3. Return the constructed string.
class Solution:
    def maximumOddBinaryNumber(self, s: str) -> str:
        count = 0
        for c in s:
            if c == "1":
                count += 1

        return (count - 1) * "1" + (len(s) - count) * "0" + "1"

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

3. Two Pointers

Intuition

We can rearrange the string in-place using a two-pointer technique similar to the partition step in quicksort. We move all 1s to the left side of the array, then swap one 1 to the last position.

This achieves the same result as sorting but with a single O(n) pass.

Algorithm

  1. Convert the string to a character array.
  2. Use a left pointer starting at 0. Iterate through the array with index i.
  3. Whenever s[i] == '1', swap s[i] with s[left] and increment left.
  4. After the loop, all 1s are at positions 0 to left - 1.
  5. Swap s[left - 1] with s[n - 1] to place one 1 at the end.
  6. Return the resulting string.
class Solution:
    def maximumOddBinaryNumber(self, s: str) -> str:
        s = [c for c in s]
        left = 0

        for i in range(len(s)):
            if s[i] == "1":
                s[i], s[left] = s[left], s[i]
                left += 1
        s[left - 1], s[len(s) - 1] = s[len(s) - 1], s[left - 1]
        return "".join(s)

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

Common Pitfalls

Forgetting That Odd Numbers Must End With 1

The defining property of an odd binary number is that its least significant bit (last character) must be '1'. A common mistake is placing all 1s at the beginning without reserving one for the end, resulting in an even number. Always ensure exactly one '1' is placed at the last position.

Assuming the Input Always Has Multiple 1s

When the input contains only a single '1', the only valid output is that '1' at the end with all '0's before it. Failing to handle this edge case (e.g., trying to place count - 1 ones when count is 1) can cause index errors or incorrect string construction.