Special Binary String
Hard
Topics
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
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.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
Input: s = "10" Output: "10" Explanation: A single special pair with nothing to swap.
Example 3
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
- Split
sinto top-level groups: scan with a counter,+1for1and-1for0, and close a group each time the counter returns to zero. - For each group, strip its outer
1and0, recurse on the inside, and wrap the result back up. - Sort the finished groups in descending order.
- 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
10rather than where the counter returns to zero."1100"is one group, not two. - Forgetting to strip and re-add the outer
1and0. 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)import java.util.*;
class Solution {
public String makeLargestSpecial(String s) {
return largest(s);
}
private String largest(String text) {
List<String> groups = new ArrayList<>();
int count = 0, start = 0;
for (int i = 0; i < text.length(); i++) {
count += text.charAt(i) == '1' ? 1 : -1;
if (count == 0) {
groups.add("1" + largest(text.substring(start + 1, i)) + "0");
start = i + 1;
}
}
groups.sort(Comparator.reverseOrder());
StringBuilder out = new StringBuilder();
for (String g : groups) out.append(g);
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string makeLargestSpecial(string s) {
function<string(const string&)> largest = [&](const string& text) -> string {
vector<string> groups;
int count = 0;
size_t start = 0;
for (size_t i = 0; i < text.size(); i++) {
count += text[i] == '1' ? 1 : -1;
if (count == 0) {
groups.push_back("1" + largest(text.substr(start + 1, i - start - 1)) + "0");
start = i + 1;
}
}
sort(groups.begin(), groups.end(), greater<string>());
string out;
for (const string& g : groups) out += g;
return out;
};
return largest(s);
}
};/**
* @param {string} s
* @return {string}
*/ var makeLargestSpecial = function(s) {
const largest = (text) => {
const groups = [];
let count = 0, start = 0;
for (let i = 0; i < text.length; i++) {
count += text[i] === "1" ? 1 : -1;
if (count === 0) {
groups.push("1" + largest(text.slice(start + 1, i)) + "0");
start = i + 1;
}
}
groups.sort().reverse();
return groups.join("");
};
return largest(s);
};