2864. Maximum Odd Binary Number LeetCode Solution

In this guide, you will get 2864. Maximum Odd Binary Number LeetCode Solution with the best time and space complexity. The solution to Maximum Odd Binary Number problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Maximum Odd Binary Number solution in C++
  4. Maximum Odd Binary Number solution in Java
  5. Maximum Odd Binary Number solution in Python
  6. Additional Resources
2864. Maximum Odd Binary Number LeetCode Solution image

Problem Statement of Maximum Odd Binary Number

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 <= 100
s consists only of '0' and '1'.
s contains at least one '1'.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)
See also  1374. Generate a String With Characters That Have Odd Counts LeetCode Solution

2864. Maximum Odd Binary Number LeetCode Solution in C++

class Solution {
 public:
  string maximumOddBinaryNumber(string s) {
    const int zeros = ranges::count(s, '0');
    const int ones = s.length() - zeros;
    return string(ones - 1, '1') + string(zeros, '0') + '1';
  }
};
/* code provided by PROGIEZ */

2864. Maximum Odd Binary Number LeetCode Solution in Java

class Solution {
  public String maximumOddBinaryNumber(String s) {
    final int zeros = (int) s.chars().filter(c -> c == '0').count();
    final int ones = s.length() - zeros;
    return "1".repeat(ones - 1) + "0".repeat(zeros) + "1";
  }
}
// code provided by PROGIEZ

2864. Maximum Odd Binary Number LeetCode Solution in Python

class Solution:
  def maximumOddBinaryNumber(self, s: str) -> str:
    return '1' * (s.count('1') - 1) + '0' * s.count('0') + '1'
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.