You are given a binary string s
(such as “010”). You need to rearrange the characters of the string in such a way that it forms the largest possible odd binary number. A binary number is odd if its last digit is 1
.
Assuming the input will always contain at least one ‘1’ and the output should be the binary string.
def maximumOddBinaryNumber(s: str) -> str:
# Count the number of '1's and '0's
ones = s.count('1')
zeros = s.count('0')
# Form the largest number by putting (ones-1) '1's, then all '0's, and end with one '1'.
result = '1' * (ones - 1) + '0' * zeros + '1'
return result
# Example Usage
s = "010"
print(maximumOddBinaryNumber(s)) # Output should be "101"
1
s and 0
s: (O(n)), where (n) is the length of the string.Thus, the overall time complexity of the solution is (O(n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?