Algorithm


Problem Name: 761. Special Binary String

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"

 

Constraints:

  • 1 <= s.length <= 50
  • s[i] is either '0' or '1'.
  • s is a special binary string.

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const makeLargestSpecial = function(S) {
  let count = 0, i = 0
  const res = []
  for(let j = 0, len = S.length; i  <  len; j++) {
    if(S.charAt(j) === '1') count++
    else count--
    if(count === 0) {
      res.push('1' + makeLargestSpecial(S.substring(i + 1, j)) + '0')
      i = j + 1
    }
  }
  return res.sort().reverse().join('')
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "11011000"

Output

x
+
cmd
"11100100"

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def makeLargestSpecial(self, S: str) -> str:
        count = i = 0
        res = []
        for j, v in enumerate(S):
            count = count + 1 if v=='1' else count - 1
            if count == 0:
                res.append('1' + self.makeLargestSpecial(S[i + 1:j]) + '0')
                i = j + 1
        return ''.join(sorted(res)[::-1])
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "11011000"

Output

x
+
cmd
"11100100"
Advertisements

Demonstration


Previous
#757 Leetcode Set Intersection Size At Least Two Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#762 Leetcode Prime Number of Set Bits in Binary Representation Solution in C, C++, Java, JavaScript, Python, C# Leetcode