Remove K-Balanced Substrings

You are given a string s consisting of '(' and ')', and an integer k.

A string is k-balanced if it is exactly k consecutive '(' followed by k consecutive ')', i.e., '(' * k + ')' * k.

For example, if k = 3, k-balanced is "((()))".

You must repeatedly remove all non-overlapping k-balanced substrings from s, and then join the remaining parts. Continue this process until no k-balanced substring exists.

Return the final string after all possible removals.

Example 1
Inputs = "(())", k = 1
Output""
For k = 1, the k-balanced substring is "()", and repeatedly removing it from "(())" leaves the empty string.
Example 2
Inputs = "(()(", k = 1
Output"(("
For k = 1, removing the only k-balanced substring "()" from "(()(" leaves "((", which contains no further k-balanced substring.

Constraints

  • 2 <= s.length <= 10^5
  • s consists only of '(' and ')'.
  • 1 <= k <= s.length / 2

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate