LeetCode 1702: Maximum Binary String After Change Solution

Master LeetCode problem 1702 (Maximum Binary String After Change), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1702. Maximum Binary String After Change

Problem Explanation

Explanation:

To obtain the maximum binary string after applying the given operations, we need to maximize the number of 1's in the resulting string. The strategy is to first count the number of leading zeros in the input binary string. If there are no leading zeros, the input binary string is already the maximum binary string. Otherwise, based on the position of the first occurrence of '10' in the remaining part of the binary string after removing leading zeros, we construct the maximum binary string.

  1. Count the number of leading zeros in the input binary string.
  2. If there are no leading zeros, the input binary string is already the maximum binary string.
  3. Otherwise, find the first occurrence of '10' in the remaining part of the binary string after removing leading zeros.
  4. Construct the maximum binary string by appending '1's before the '10' and then appending the remaining binary string after '10'.

The time complexity of this approach is O(n), where n is the length of the binary string, and the space complexity is O(1).

:

Solution Code

class Solution {
    public String maximumBinaryString(String binary) {
        int zeros = 0;
        int n = binary.length();
        for (int i = 0; i < n && binary.charAt(i) == '0'; i++) {
            zeros++;
        }
        if (zeros == n) {
            return binary;
        }
        int ones = n - zeros - 1;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < zeros; i++) {
            sb.append('1');
        }
        sb.append('0');
        for (int i = 0; i < ones; i++) {
            sb.append('1');
        }
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1702 (Maximum Binary String After Change)?

This page provides optimized solutions for LeetCode problem 1702 (Maximum Binary String After Change) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1702 (Maximum Binary String After Change)?

The time complexity for LeetCode 1702 (Maximum Binary String After Change) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1702 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1702 in Java, C++, or Python.

Back to LeetCode Solutions