Sponsored
Sponsored
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.
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.
1function maxOddBinaryNumber(s) {
2 const ones = s.split('').filter(c => c === '1').length;
3 const zeros = s.split('').filter(c => c === '0').length;
4 return '1'.repeat(ones - 1) + '0'.repeat(zeros) + '1';
5}
6
7const s = "0101";
8console.log(maxOddBinaryNumber(s));
JavaScript efficiently counts '1's and '0's using Array functions. It constructs the output using the necessary repetitions.
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.
Time Complexity: O(n log n) for sorting.
Space Complexity: O(1) assuming sorting in place is allowed.
1
Solve with full IDE support and test cases
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.