Problem · String

Balanced Split String with Wildcards

Learn this problem
â—Ź MediumTwo SigmaOA

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) → int

Examples

Example 1

s = "?()?[?"return = 2

The string has two valid splits:

  1. s1 = "?(" and s2 = ")?[?". Replace the ? in s1 with ) so s1 can be rearranged into (). Replace the ? characters in s2 with ( and ], so s2 can be rearranged into ()[].
  2. s1 = "?()?" and s2 = "[?". Replace the ? characters in s1 with [ and ], so s1 can be rearranged into ()[]. Replace the ? in s2 with ] to make [].

Therefore, the total number of valid splits is 2.

Constraints

  • 4 <= length of s <= 10^5
  • s contains only (, ), [, ], and ?.

More Two Sigma problems

drafts saved locally
public int countBalancedSplits(String s) {
  // write your code here
}
s"?()?[?"
expected2
checking account