#2864
Maximum Odd Binary Number
EasyMathStringGreedyGreedyString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the fact that to create the largest odd binary number, we should place all '1's at the front, except for one '1' which must be at the end to ensure the number is odd.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of '1's and '0's in the string.
- 2Step 2: If there's at least one '1', place all '1's except one at the front.
- 3Step 3: Place one '1' at the end and fill the rest with '0's.
solution.py4 lines
1def maxOddBinary(s):
2 count1 = s.count('1')
3 count0 = s.count('0')
4 return '1' * (count1 - 1) + '0' * count0 + '1' if count1 > 0 else ''ℹ
Complexity note: The time complexity is O(n) because we traverse the string once to count '1's and '0's. The space complexity is O(n) due to the construction of the result string.
- 1To form the maximum odd binary number, the last digit must be '1'.
- 2The arrangement of '1's and '0's affects the overall value of the binary number.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.