Special Binary String - Solution & Explanation
Problem Statement
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.
Example 1:
Input: s = "11011000" Output: "11100100" Explanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped. This is the lexicographically largest string possible after some number of swaps.
Example 2:
Input: s = "10" Output: "10"
Constraints:
1 <= s.length <= 50s[i]is either'0'or'1'.sis a special binary string.
Approach Overview
Problem Overview: You’re given a binary string that is special: it contains the same number of 1s and 0s, and every prefix has at least as many 1s as 0s. You can swap adjacent special substrings. The goal is to rearrange the string to produce the lexicographically largest possible result.
Approach 1: Brute Force Rearrangement (Exponential Time, Exponential Space)
The naive idea is to generate all valid swaps of adjacent special substrings and track the lexicographically largest result. Each step tries every possible split where both sides remain valid special strings. This quickly explodes because the number of permutations grows exponentially with the number of segments. Time complexity is roughly O(2^n) in the worst case with large recursion trees, and space complexity is also O(2^n) due to storing generated states. This approach mainly helps understand the problem constraints but is not practical for large inputs.
Approach 2: Stack / Balanced Decomposition (O(n^2) time, O(n) space)
A special binary string behaves similarly to balanced parentheses. Iterate through the string while counting 1s and 0s. Whenever the counts match, you’ve found a minimal valid special substring. Extract these segments and store them. Each segment can then be processed recursively and combined back. While this decomposition is efficient, naive concatenation or repeated comparisons during reordering can push the time complexity toward O(n^2). This technique highlights the structural similarity between this problem and balanced structures often discussed in stack problems.
Approach 3: Recursive Decomposition and Sorting (O(n log n) time, O(n) space)
The optimal strategy recursively breaks the string into its smallest special components. Scan the string while maintaining a counter: increment for 1 and decrement for 0. When the counter returns to zero, you’ve identified a complete special substring. Recursively solve the inner portion s[i+1:j], wrap it with 1 and 0, and add the result to a list.
After extracting all components, sort them in descending lexicographic order and concatenate. Larger segments starting with more leading 1s produce bigger lexicographic values, so sorting ensures the globally optimal arrangement. The scan is linear and the sorting step dominates with O(k log k) where k is the number of segments, leading to overall O(n log n) time and O(n) recursion space.
This technique combines ideas from string manipulation and divide‑and‑conquer recursion. The recursive structure ensures every nested special substring is maximized before assembling the final answer.
Recommended for interviews: Recursive decomposition with sorting is the expected solution. It demonstrates recognition of the balanced structure, correct recursive segmentation, and greedy ordering for lexicographic maximization. Interviewers typically want to see how you detect valid segments and recursively optimize them using recursion.
Approach 1: Recursive Decomposition and Sorting
This approach leverages recursion to decompose the special binary string into smaller special substrings, sort these components, and then rebuild the string to achieve the lexicographically largest string. This works because by sorting the special substrings in descending order, larger lexicographical strings are formed.
The function recursively decomposes the string whenever a balance point is reached, i.e., when the count of '1's and '0's becomes zero. Once parts are decomposed, they are sorted in reverse (descending) order to achieve the lexicographically largest string.
Complexity
Time Complexity: O(n^2), where n is the length of the string, due to recursive decomposition and sorting.
Space Complexity: O(n), for storing the results and recursion stack.
Approach 2: Recursion + Sorting
We can treat the special binary sequence as "valid parentheses", where 1 represents an opening parenthesis and 0 represents a closing parenthesis. For example, "11011000" can be viewed as "(()(()))".
Swapping two consecutive non-empty special substrings is equivalent to swapping two adjacent valid parentheses. We can use recursion to solve this problem.
We treat each "valid parenthesis" in string s as a part, process it recursively, and finally sort them to get the final answer.
The time complexity is O(n^2), and the space complexity is O(n), where n is the length of string s.
Code
Python
Java
C++
Go
TypeScript
Complexity Comparison
| Approach | Complexity |
|---|---|
| Recursive Decomposition and Sorting | Time Complexity: O(n^2), where n is the length of the string, due to recursive decomposition and sorting. Space Complexity: O(n), for storing the results and recursion stack. |
| Recursion + Sorting | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Rearrangement | O(2^n) | O(2^n) | Understanding the structure of valid special substrings; not practical for real constraints |
| Stack / Balanced Decomposition | O(n^2) | O(n) | When identifying minimal balanced segments before optimization |
| Recursive Decomposition and Sorting | O(n log n) | O(n) | Optimal solution for interviews and production implementations |
Video Solution
Special Binary String | Detailed Intuition | Dry Run | Leetcode 761 | codestorywithMIK • codestorywithMIK • 12,358 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Special Binary String easy or hard?
Special Binary String Python/Java solution
How to solve Special Binary String in O(n)?
What is the best approach for Special Binary String?
Is Special Binary String asked at Google/Amazon/Meta?
What data structure is used in Special Binary String?
What is the time complexity of Special Binary String?
Ready to solve this problem?
Practice Special Binary String with our built-in code editor and test cases.
Practice on FleetCodeProblem Info
Table of Contents
Practice this problem
Open in Editor