Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum binary string after change in python
Given a binary string, we can apply two types of operations any number of times to maximize its numeric value:
Replace substring "00" with "10"
Replace substring "10" with "01"
We need to find the maximum possible binary string after applying these operations.
Understanding the Problem
The key insight is that we want to move as many 1s as possible to the left (higher positions) while keeping at least one 0 in the string. The operations allow us to:
"00" ? "10": Creates a 1 to the left of a 0
"10" ? "01": Moves a 1 to the right of a 0
Algorithm
If we have fewer than 2 zeros, no optimization is possible. Otherwise, we can move all 1s to optimal positions, leaving exactly one 0 in the string ?
def solve(s):
length = len(s)
zeros = s.count('0')
# If less than 2 zeros, no optimization possible
if zeros < 2:
return s
# Remove leading 1s to find the core pattern
s = s.lstrip('1')
leading_ones = length - len(s)
# Calculate optimal distribution
leading_ones += zeros - 1 # Move zeros-1 ones to the front
trailing_ones = length - leading_ones - 1 # Remaining ones go to the end
# Build the result: leading 1s + one 0 + trailing 1s
answer_left = '1' * leading_ones
answer_right = '1' * trailing_ones
return ''.join([answer_left, '0', answer_right])
# Test with the example
s = "001100"
result = solve(s)
print(f"Input: {s}")
print(f"Output: {result}")
Input: 001100 Output: 111011
Step-by-Step Transformation
Let's trace how "001100" becomes "111011" ?
def show_transformation():
steps = [
"001100", # Original
"101100", # 00 ? 10
"101010", # 10 ? 01 (middle)
"101001", # 10 ? 01 (right)
"100101", # 10 ? 01 (left)
"110011", # 00 ? 10 (left)
"111011" # 10 ? 01 (middle)
]
print("Transformation steps:")
for i, step in enumerate(steps):
print(f"Step {i}: {step}")
show_transformation()
Transformation steps: Step 0: 001100 Step 1: 101100 Step 2: 101010 Step 3: 101001 Step 4: 100101 Step 5: 110011 Step 6: 111011
Additional Examples
Testing with different input patterns ?
test_cases = ["001100", "1100", "000", "101", "1111"]
for test in test_cases:
result = solve(test)
print(f"'{test}' ? '{result}'")
'001100' ? '111011' '1100' ? '1101' '000' ? '110' '101' ? '101' '1111' ? '1111'
Conclusion
The algorithm maximizes the binary value by moving all possible 1s to the front, leaving exactly one 0 in the optimal position. When fewer than 2 zeros exist, no improvement is possible.
---