Special Binary String - Problem
Special binary strings are binary strings with the following two properties:
- The number of
0's is equal to the number of1's. - Every prefix of the binary string has at least as many
1's as0'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.
Input & Output
Example 1 — Basic Rearrangement
$
Input:
s = "11011000"
›
Output:
"11100100"
💡 Note:
We can identify groups "110" and "1100" and "00". After sorting optimally: "1100" + "110" + "00" = "11100100".
Example 2 — Already Optimal
$
Input:
s = "10"
›
Output:
"10"
💡 Note:
The string is already the lexicographically largest possible since it's a single balanced group.
Example 3 — Multiple Groups
$
Input:
s = "1100101001"
›
Output:
"1100101001"
💡 Note:
Groups are "1100", "10", "1001". After sorting: "1100" comes first, then "1001", then "10" giving "1100100110".
Constraints
- 1 ≤ s.length ≤ 1000
- s consists of only '0' and '1'
- s is guaranteed to be a special binary string
Visualization
Tap to expand
Understanding the Visualization
1
Input
Special binary string with equal 1s and 0s, valid prefixes
2
Process
Identify balanced groups and sort them optimally
3
Output
Lexicographically largest possible string
Key Takeaway
🎯 Key Insight: Treat 1s and 0s like balanced parentheses - recursively optimize independent groups and sort them for maximum lexicographic value
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code