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 = "010" Output: "001" Explanation: Because there is just one '1', it must be in the last position. So the answer is "001".
Example 2:
Input: s = "0101" 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".
Constraints:
1 <= s.length <= 100s consists only of '0' and '1'.s contains at least one '1'.To form the maximum odd binary number from a given binary string, observe that the binary number should have '1' at the end to be odd. Among the remaining bits, arrange as many '1's as possible at the leading positions while maintaining the '1' at the end. This approach involves counting the occurrences of '1' and '0', then constructing the number.
The program first counts the '1's and '0's. It reserves one '1' for the end to make the number odd. The rest of the '1's are placed at the beginning, and '0's fill the remaining positions before the final '1'.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string as it needs one pass to count and another to construct.
Space Complexity: O(1) for the counting variables.
A different approach involves sorting the binary string while ensuring a '1' is at the end. To maximize the binary number, the initial part of the string should consist of leading '1's followed by '0's, then append a single '1' at the end to turn the number odd.
This solution sorts the string in descending order and ensures '1' is moved to the last position. Sorting places '1's before '0's. The trailing '1' ensures oddness.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) for sorting.
Space Complexity: O(1) assuming sorting in place is allowed.
| Approach | Complexity |
|---|---|
| Approach 1: Sort and Place Last '1' | Time Complexity: O(n), where n is the length of the string as it needs one pass to count and another to construct. |
| Approach 2: Using Sorting | Time Complexity: O(n log n) for sorting. |
Maximum Odd Binary Number - Leetcode 2864 - Python • NeetCodeIO • 6,569 views views
Watch 9 more video solutions →Practice Maximum Odd Binary Number with our built-in code editor and test cases.
Practice on FleetCode