1705. Every Balanced Slice

Medium3.5 points estimatedStackStringDynamic Programming

A string s is made only of the characters '(' and ')'. A bracket sequence is balanced when every '(' is closed by a later ')' and every ')' closes an earlier '('; for example "(()())" and "()()" are balanced while ")(" and "(()" are not.

Return how many substrings of s (contiguous pieces, counted by position, so equal substrings at different places count separately) are balanced and non-empty. The answer can exceed 32 bits, so return it as a long. Checking every substring costs O(n^2) or worse; instead scan with a stack of indices of open brackets. When a ')' at index i closes the '(' at index j, the number of balanced substrings ending at i is 1 plus the number ending at j - 1. The intended solution runs in O(n) time with O(n) extra space.

Example 1

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

The balanced substrings are "()" at positions 0-1, "()" at positions 2-3 and the whole string "()()", so the answer is 3.

Example 2

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

"(())" contains the inner "()" and the whole string, which is 2.

Example 3

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

A string that starts with ')' and then '(' has no balanced substring, so the answer is 0.

Constraints

1 ≤ s.length ≤ 2 * 105

s consists only of '(' 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…