Special Binary String

Hard

Topics
StringRecursionDivide and Conquer

A binary string is special when it has equal numbers of 0s and 1s, and every prefix of it has at least as many 1s as 0s.

You are given a special string s. You may repeatedly choose two consecutive, non-empty special substrings of s and swap them.

Return the lexicographically largest string reachable this way.

Example 1

input1011021314050607
answer11100100
a top-level piece
A special string carries as many 1s as 0s and never runs more 0s than 1s in any prefix, which means it splits into special pieces laid side by side — 1 piece here, marked by alternating shades. Each piece is itself a 1, a special string, and a 0, so the structure repeats all the way down. The answer is the largest string reachable by rearranging pieces, which applies at every level and not just the top.
Only whole pieces may move; cutting across a piece would break the prefix rule.
Input:  s = "11011000"
Output: "11100100"
Explanation: The substrings 10 and 1100 sit side by side inside the outer pair; swapping them puts the larger first.

Example 2

input1001
answer10
a top-level piece
Input:  s = "10"
Output: "10"
Explanation: A single special pair with nothing to swap.

Example 3

input10110203
answer1100
a top-level piece
Input:  s = "1100"
Output: "1100"
Explanation: One pair wrapping another; there is no sibling to exchange it with.

Constraints

  • 1 <= s.length <= 50
  • s is a special binary string
Editorial — intuition, approach, complexity and pitfalls

Intuition

Read 1 as an opening bracket and 0 as a closing one, and "special" says exactly that the string is balanced. That reframing is the whole problem: the special substrings are the balanced groups, and swapping two consecutive ones is reordering siblings.

So s decomposes into top-level groups, each of which is 1 + an inner special string + 0. Siblings can be permuted freely by repeated adjacent swaps, so the best arrangement is simply the groups sorted into descending order.

And each group’s own inner string is a special string in its own right, with its own siblings to arrange — so the same treatment applies inside. Make each group as large as it can be first, then sort the finished groups. Doing it the other way round sorts strings that are about to change.

Sorting descending as plain strings is correct here rather than approximate, because the groups all start with 1 and end with 0 and are balanced, which rules out the prefix pathologies that make naive string ordering wrong elsewhere.

Approach

  1. Split s into top-level groups: scan with a counter, +1 for 1 and -1 for 0, and close a group each time the counter returns to zero.
  2. For each group, strip its outer 1 and 0, recurse on the inside, and wrap the result back up.
  3. Sort the finished groups in descending order.
  4. Concatenate them.

Walkthrough

s = "11011000"

scan for top-level groups
   1 1 0 1 1 0 0 0
   1 2 1 2 3 2 1 0   counter returns to 0 only at the end,
                     so the whole string is ONE group

strip the outer pair -> "101100"
   groups inside: "10" and "1100"

recurse into each
   "10"   -> "1" + (nothing) + "0"      = "10"
   "1100" -> "1" + makeLargest("10") + "0" = "1100"

sort descending: "1100", "10"
join: "110010"

wrap back up: "1" + "110010" + "0" = "11100100"

Complexity

  • Time — O(n^2 log n): each recursion level handles the whole string and sorts its groups; the depth is bounded by the nesting.
  • Space — O(n^2): the substrings built at each level, plus the recursion depth.

Common Pitfalls

  • Sorting the groups before recursing into them. A group’s order can change once its own insides are rearranged, so the sort has to come last.
  • Sorting ascending, or sorting the characters. The groups are sorted descending as whole strings.
  • Splitting at every 10 rather than where the counter returns to zero. "1100" is one group, not two.
  • Forgetting to strip and re-add the outer 1 and 0. Recursing on the whole group gives back the same group and never terminates.

Full Solution — all languages

class Solution:
    def makeLargestSpecial(self, s):
        def largest(text):
            groups = []
            count = start = 0
            for i, c in enumerate(text):
                count += 1 if c == "1" else -1
                if count == 0:
                    groups.append("1" + largest(text[start + 1:i]) + "0")
                    start = i + 1
            groups.sort(reverse=True)
            return "".join(groups)

        return largest(s)
SensAI
Beta
Tap the mic to stop voice mode