Problem · String
Balanced Split String with Wildcards
Learn this problemProblem statement
Determine the number of ways a string containing the characters (, ), [, ], and ? can be divided into two non-empty substrings such that each substring can be rearranged to form a balanced string.
The ? characters can be replaced with any bracket character—(, ), [, or ]—as needed to achieve balance.
The two substrings together must cover the entire original string and cannot overlap. A substring is a contiguous block of the original string.
Balanced strings
A balanced string has all brackets properly matched and nested. For example, [], (), and [()] are balanced. Strings such as (], ([), and ] are not.
Function
countBalancedSplits(s: String) → intExamples
Example 1
s = "?()?[?"return = 2The string has two valid splits:
s1 = "?("ands2 = ")?[?". Replace the?ins1with)sos1can be rearranged into(). Replace the?characters ins2with(and], sos2can be rearranged into()[].s1 = "?()?"ands2 = "[?". Replace the?characters ins1with[and], sos1can be rearranged into()[]. Replace the?ins2with]to make[].
Therefore, the total number of valid splits is 2.
Constraints
4 <= length of s <= 10^5scontains only(,),[,], and?.
More Two Sigma problems
- Closest ColorOA · Seen Jul 2026
- Linear InterpolatorOA · Seen Jun 2026
- Online No-Intercept Linear RegressionOA · Seen Jun 2026
- Piecewise Linear Interpolation and ExtrapolationOA · Seen May 2026
- Sewer Drainage PartitionOA · Seen Mar 2026
- Calculate y/x using PatchOA · Seen Nov 2025
- Nums That Are Divisible by N 🍋Seen Mar 2024
- Replacing Val 🍓Seen Mar 2024