Balanced Split String with Wildcards
Updated
Problem 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 Online Assessment questions
- IPO Share AllocationOA · Seen Sep 2026
- Sewer Drainage PartitionOA · Seen Sep 2026
- Daily Temperature By TownOA · Seen Sep 2026
- Linear InterpolatorOA · Seen Sep 2026
- Online No-Intercept Linear RegressionOA · Seen Sep 2026
- Closest ColorOA · Seen Aug 2026
- Piecewise Linear Interpolation and ExtrapolationOA · Seen May 2026
- Calculate y/x using PatchOA · Seen Nov 2025
- Nums That Are Divisible by N 🍋OA · Seen Mar 2024
- Replacing Val 🍓OA · Seen Mar 2024
Similar questions at other companies
- Earliest Time to Schedule a MeetingMathWorks · OAMathWorks interview questions
- Earliest Meeting Start on a 24-Hour ClockIMC Trading · OAIMC Trading interview questions
- Earliest Time to Schedule a MeetingMicrosoft · OAMicrosoft interview questions
- Maximum Equalized Substrings After One Adjacent SwapVisa · OAVisa interview questions
- Maximum Redundancy After One Segment FlipBloomberg LP · OABloomberg LP interview questions
- Longest Balanced Substring After One SwapTekion · OATekion interview questions
- Shortest Compressed Length After RemovalDRW · OADRW interview questions
- Count Special StringsAmazon · OA
- Binary Palindromic Subsequences of Length 5Citadel · OACitadel interview questions
- Maximum Positive FeedbackTikTok · OATikTok interview questions