1209. Balanced Piece Count

Medium3.5 points estimatedStackDynamic ProgrammingString

A code editor highlights matching brackets, and a plugin wants to know how many highlighted regions a line contains. You are given a string s made only of the characters ( and ). A substring is a balanced piece when every bracket in it is matched and the brackets are properly nested, such as (), (()) or ()().

Count every balanced piece. Pieces at different positions are counted separately even when their text is identical. Return the total as a long, because it can exceed the 32-bit range. Aim for O(n) time and O(n) extra space, since checking every substring one by one is far too slow for the longest inputs.

Example 1

Input:
s = "(()())"
Output:
4
Explanation:

The pieces are the two inner (), the middle ()() and the whole string, so the answer is 4.

Example 2

Input:
s = "()()"
Output:
3
Explanation:

The pieces are each () and the whole ()(), so the answer is 3.

Example 3

Input:
s = ")()("
Output:
1
Explanation:

Only the middle () is balanced, so the answer is 1.

Constraints

1 ≤ s.length ≤ 2 * 105

s contains only '(' and ')'

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…