Leetcode 2864. Maximum Odd Binary Number
You are given a binary string s (possibly with leading zeros), which represents a binary number. Your task is to rearrange the bits in the string to get the maximum odd binary number possible. The output should also be a binary string. A binary number is odd if its last digit is 1.
s = "010"
Output: s = "100"s = "1011"
Output: s = "1110"s be empty?
s will have at least one character.s?
s will only contain ‘0’ and ‘1’ characters.s?
0s and 1s in the string: Determine the frequency of 0s and 1s in the string s.1s as possible at the most significant positions.1.1s at the beginning (except one which will be placed at the end to ensure odd number).0s next.1 to ensure the number is odd.public class MaximumOddBinaryNumber {
public static String maximumOddBinaryNumber(String s) {
int count1s = 0;
int count0s = 0;
for(char c : s.toCharArray()) {
if (c == '1') {
count1s++;
} else {
count0s++;
}
}
if (count1s == 0) {
return "0"; // No way to get an odd number, default to "0" (though constraints guarantee at least one character).
}
StringBuilder result = new StringBuilder();
// Add all but one '1' at the start
for (int i = 0; i < count1s - 1; i++) {
result.append('1');
}
// Add all '0's
for (int i = 0; i < count0s; i++) {
result.append('0');
}
// Finally, add the last '1' to make the number odd
result.append('1');
return result.toString();
}
public static void main(String[] args) {
String s1 = "010";
System.out.println(maximumOddBinaryNumber(s1)); // Output: "100"
String s2 = "1011";
System.out.println(maximumOddBinaryNumber(s2)); // Output: "1110"
}
}
The time complexity of the solution is O(n), where n is the length of the string s. This complexity arises from:
This approach ensures that the solution is efficient and works within the constraints of the problem.
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?