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 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.

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
Special Binary String - Recursive Divide and Conquer INPUT Special Binary String: 1 1 0 1 1 0 0 0 s = "11011000" Properties: 1. Equal 0s and 1s (4 each) 2. Every prefix has >= 1s than 0s Prefix Counts (1s - 0s): Index: 0 1 2 3 4 5 6 7 Count: 1 2 1 2 3 2 1 0 Structure (like parentheses): 1(1(10)00) --> 1(...)0 1 = open, 0 = close ALGORITHM STEPS 1 Find Special Substrings Track balance (1s - 0s) When balance = 0, found one 2 Recursively Process For each 1(inner)0 pattern Recurse on inner part 3 Sort Descending Sort special substrings in reverse order for max 4 Concatenate Result Join sorted substrings to form largest string Decomposition: "11011000" --> "1[1[10]00]0" = "1[X]0" X = "101000" recurse FINAL RESULT Lexicographically Largest: 1 1 1 0 0 1 0 0 "11100100" Swap Operations: Original: "11011000" Parts: "1100" + "1100" Inner: "10" + "10" Sort desc --> swap Result: "11100100" Verification [OK] - Equal 0s and 1s: OK - Valid prefixes: OK Key Insight: Special binary strings are like balanced parentheses: 1 = '(' and 0 = ')'. Each valid string has form 1(inner)0. Recursively process inner parts, then sort all special substrings in descending order to maximize lexicographic value (more 1s first). TutorialsPoint - Special Binary String | Recursive Divide and Conquer Approach
Asked in
Google 25 Facebook 18
18.5K Views
Medium Frequency
~35 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen