Special Binary String LeetCode Solution

Last updated on January 18th, 2025 at 09:51 pm

Here, we see a Special Binary String LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Greedy, Heap

Level of Question

Hard

Special Binary String LeetCode Solution

Special Binary String LeetCode Solution

1. Problem Statement

Special binary strings are binary strings with the following two properties:

  • The number of 0‘s is equal to the number of 1‘s.
  • Every prefix of the binary string has at least as many 1‘s as 0‘s.

You are given a special binary string s.

A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.

Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.

Example 1:
Input: s = “11011000” Output: “11100100” Explanation: The strings “10” [occuring at s[1]] and “1100” [at s[3]] are swapped. This is the lexicographically largest string possible after some number of swaps.

Example 2:
Input: s = “10” Output: “10”

2. Coding Pattern Used in Solution

The coding pattern used in this code is “Divide and Conquer”. The problem is recursively broken down into smaller subproblems (decomposing the string into “special binary strings”), solved independently, and then combined to form the final result.

3. Code Implementation in Different Languages

3.1 Special Binary String C++

class Solution {
 public:
  string makeLargestSpecial(string s) {
    vector specials;
    int count = 0;

    for (int i = 0, j = 0; j < s.length(); ++j) {
      count += s[j] == '1' ? 1 : -1;
      if (count == 0) {
        const string& inner = s.substr(i + 1, j - i - 1);
        specials.push_back('1' + makeLargestSpecial(inner) + '0');
        i = j + 1;
      }
    }
    sort(begin(specials), end(specials), greater<>());
    return join(specials);
  }
 private:
  string join(const vector& specials) {
    string joined;
    for (const string& special : specials)
      joined += special;
    return joined;
  }
};

3.2 Special Binary String Java

class Solution {
    public String makeLargestSpecial(String s) {
        int count = 0, i = 0;
        List<String> res = new ArrayList<String>();
        for (int j = 0; j < s.length(); ++j) {
          if (s.charAt(j) == '1') count++;
          else count--;
          if (count == 0) {
            res.add('1' + makeLargestSpecial(s.substring(i + 1, j)) + '0');
            i = j + 1;
          }
        }
        Collections.sort(res, Collections.reverseOrder());
        return String.join("", res);
    }
}

3.3 Special Binary String JavaScript

var makeLargestSpecial = function (s) {
    if (s.length < 2) {
        return s;
    }
    let start = 0;
    let count = 0;
    let result = [];
    for (let i = 0; i < s.length; i++) {
        count += s[i] === '1' ? 1 : -1;
        if (!count) {
            const special = makeLargestSpecial(s.substring(start + 1, i));
            result.push('1' + special + '0');
            start = i + 1;
        }
    }
    result.sort((a, b) => {
        if (a === b) {
            return 0;
        }
        let i = 0;
        while (a[i] && b[i] && a[i] === b[i]) {
            i++;
        }
        if (a[i + 1] && !b[i + 1]) {
            return -1;
        }
        if (!a[i + 1] && b[i + 1]) {
            return 1;
        }
        return b[i] - a[i];
    })
    return result.join('');
};

3.4 Special Binary String Python

class Solution(object):
    def makeLargestSpecial(self, s):
        def decompose(s):
            i, count = 0, 0
            res = []
            for j in range(len(s)):
                count += 1 if s[j] == '1' else -1
                if count == 0:
                    res.append('1' + decompose(s[i+1:j]) + '0')
                    i = j + 1
            res.sort(reverse=True)
            return ''.join(res)
        
        return decompose(s)

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n2)O(n)
JavaO(n2)O(n)
JavaScriptO(n2)O(n)
PythonO(n2)O(n)
Scroll to Top