KatInterview

763. Special Binary String

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the lexicographically largest special binary string by swapping adjacent special substrings. A special binary string has an equal number of '1's and '0's, and every prefix has at least as many '1's as '0's. This structure is analogous to valid parentheses strings, where '1' corresponds to '(' and '0' to ')'.

Solution

Special Binary String in Python

class Solution:
    def makeLargestSpecial(self, s: str) -> str:
        # A list to store the largest forms of the top-level special string components of s.
        parts = []
        count = 0
        start = 0  # The starting index of the current component.

        for i, char in enumerate(s):
            if char == '1':
                count += 1
            else:
                count -= 1
            
            # When count is 0, we've found a complete special string component.
            if count == 0:
                # The component is s[start:i+1].
                # Its inner part is s[start+1:i].
                inner = s[start+1:i]
                # Recursively find the largest special form of the inner part.
                largest_inner = self.makeLargestSpecial(inner)
                # Construct the largest form of the current component and add to our list.
                parts.append('1' + largest_inner + '0')
                # Move to the start of the next component.
                start = i + 1
        
        # Sort the components in lexicographically descending order.
        parts.sort(reverse=True)
        
        # Join them to get the final result.
        return "".join(parts)

Special Binary String in Java

class Solution {
    public String makeLargestSpecial(String s) {
        // Base case: an empty string is a special string, its largest form is itself.
        if (s.isEmpty()) {
            return "";
        }

        List<String> parts = new ArrayList<>();
        int count = 0;
        int start = 0; // The starting index of the current component.

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1') {
                count++;
            } else {
                count--;
            }

            // When count is 0, we've found a complete special string component.
            if (count == 0) {
                // The component is s.substring(start, i + 1).
                // Its inner part is s.substring(start + 1, i).
                String inner = s.substring(start + 1, i);
                // Recursively find the largest special form of the inner part.
                String largestInner = makeLargestSpecial(inner);
                // Construct the largest form of the current component and add to list.
                parts.add("1" + largestInner + "0");
                // Move to the start of the next component.
                start = i + 1;
            }
        }

        // Sort the found components in lexicographically descending order.
        Collections.sort(parts, Collections.reverseOrder());

        // Concatenate the sorted parts to get the final result.
        return String.join("", parts);
    }
}

Special Binary String in C++

class Solution {
public:
    string makeLargestSpecial(string s) {
        // Base case: an empty string is a special string, its largest form is itself.
        if (s.empty()) {
            return "";
        }

        vector<string> parts;
        int count = 0;
        int start = 0; // The starting index of the current component.

        for (int i = 0; i < s.length(); ++i) {
            if (s[i] == '1') {
                count++;
            } else {
                count--;
            }

            // When count is 0, we've found a complete special string component.
            if (count == 0) {
                // The component is s.substr(start, i - start + 1).
                // Its inner part is s.substr(start + 1, i - start - 1).
                string inner = s.substr(start + 1, i - start - 1);
                // Recursively find the largest special form of the inner part.
                string largest_inner = makeLargestSpecial(inner);
                // Construct the largest form of the current component and add to list.
                parts.push_back("1" + largest_inner + "0");
                // Move to the start of the next component.
                start = i + 1;
            }
        }

        // Sort the found components in lexicographically descending order.
        sort(parts.begin(), parts.end(), greater<string>());

        // Concatenate the sorted parts to get the final result.
        string result = "";
        for (const string& part : parts) {
            result += part;
        }

        return result;
    }
};

Special Binary String in TypeScript

function makeLargestSpecial(s: string): string {
    // Base case: an empty string is a special string, its largest form is itself.
    if (s.length === 0) {
        return "";
    }

    const parts: string[] = [];
    let count = 0;
    let start = 0; // The starting index of the current component.

    for (let i = 0; i < s.length; i++) {
        if (s[i] === '1') {
            count++;
        } else {
            count--;
        }

        // When count is 0, we've found a complete special string component.
        if (count === 0) {
            // The component is s.substring(start, i + 1).
            // Its inner part is s.substring(start + 1, i).
            const inner = s.substring(start + 1, i);
            // Recursively find the largest special form of the inner part.
            const largestInner = makeLargestSpecial(inner);
            // Construct the largest form of the current component and add to list.
            parts.push('1' + largestInner + '0');
            // Move to the start of the next component.
            start = i + 1;
        }
    }

    // Sort the found components in lexicographically descending order.
    // b.localeCompare(a) provides descending sort for strings.
    parts.sort((a, b) => b.localeCompare(a));

    // Concatenate the sorted parts to get the final result.
    return parts.join('');
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.