Skip to content
Problem 761 · LeetCode 761(opens in a new tab)

Special Binary String

HardRecursion

A binary string is special when it has as many 1s as 0s, and no prefix of it has more 0s than 1s. Think of 1 as an opening bracket and 0 as a closing one: a special string is a balanced bracket sequence.

You are given a special string s. In one move you may pick two special substrings that sit right next to each other (the second starts where the first ends) and swap them. Make as many moves as you like, and return the lexicographically largest string you can reach.

Example 1

Input:  s = "10110100"
Output: "11010010"
Why:    swap "10" with the "110100" that follows it
2 more examples and the constraints

Example 2

Input:  s = "10"
Output: "10"
Why:    nothing to swap

Example 3

Input:  s = "10101100"
Output: "11001010"
Why:    three blocks "10", "10", "1100"; put "1100" first

Constraints

  • 1 ≤ s.length ≤ 50
  • s contains only 0 and 1
  • s is special

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split into mountains, recurseO(n²)
  2. One pass with a stack of levelsO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for s.length = 50Verdict
Split into mountains, recurseO(n²)
Clear; rescans at each depth
One pass with a stack of levelsO(n²)
Best; reads each char once

n = s.length.

Edge cases to test

  • Shortest input. "10" is one mountain with nothing inside; return it as is.
  • One big mountain. "1" + inside + "0": the outer 1 and 0 stay put; only the inside can change.
  • Already largest. "111000" or "110010" come back unchanged.
  • Many flat blocks. "101010" has three equal mountains; any order gives the same string.
  • Deep nesting. Fifty characters can nest 25 deep; the recursion stays shallow enough.

Common mistakes

  • Sorting the mountains without first solving their insides.
  • Sorting the inside of a mountain together with its outer 1 and 0.
  • Sorting ascending, which gives the smallest string instead of the largest.

How to talk through it

  1. 1Clarify. Must swapped blocks be adjacent? Can I make any number of swaps?
  2. 2Reframe as brackets. 1 is an opening bracket and 0 a closing one; special means balanced.
  3. 3Find the structure. Top-level mountains can be reordered freely; each inside is its own smaller problem.
  4. 4Sort at every level. Solve each inside, wrap it, then sort the mountains largest first.
  5. 5Test out loud. Run "10", "10110100" and "111000" to check the base, a reorder and a no-op.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?