#1702
Maximum Binary String After Change
MediumStringGreedyGreedyString 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 we can only have at most one '0' in the final string. By counting the number of '1's and the position of the last '0', we can construct the maximum binary string directly.
⚙️
Algorithm
4 steps- 1Step 1: Count the number of '1's in the binary string.
- 2Step 2: Find the position of the last '0' in the string.
- 3Step 3: If there are no '0's, return a string of all '1's.
- 4Step 4: Construct the result string with all '1's followed by a single '0' and the remaining '1's.
solution.py6 lines
1def maximumBinaryString(binary):
2 count_one = binary.count('1')
3 last_zero_index = binary.rfind('0')
4 if last_zero_index == -1:
5 return '1' * len(binary)
6 return '1' * (last_zero_index) + '0' + '1' * (count_one - (last_zero_index + 1))ℹ
Complexity note: This complexity is linear because we only traverse the string a couple of times (once for counting '1's and once for finding the last '0').
- 1You can always reduce the binary string to at most one '0'.
- 2The maximum binary string is formed by grouping all '1's together, followed by a single '0' if present.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.