1179. Partner Bracket

Easy1.5 points estimatedStackString

A code editor highlights the closing partner of the bracket under the cursor. The string s contains only '(' and ')', and index is a 0-based position that is guaranteed to hold '('.

Return the 0-based index of the ')' that closes that bracket, meaning the first position to its right where the running balance, which starts at zero on the bracket itself, comes back to zero. If the bracket is never closed, return -1. The string as a whole need not be balanced, and brackets to the left of index are ignored.

Scan right from index with a depth counter: add one for '(' and subtract one for ')'. This takes linear time and constant space.

Example 1

Input:
s = "(()())", index = 0
Output:
5
Explanation:

The bracket at index 0 closes at index 5, after the two inner pairs.

Example 2

Input:
s = "(()())", index = 1
Output:
2
Explanation:

The bracket at index 1 closes immediately at index 2.

Example 3

Input:
s = "(((", index = 1
Output:
-1
Explanation:

No closing bracket ever balances the one at index 1, so the answer is -1.

Constraints

1 ≤ s.length ≤ 105

0 ≤ index < s.length and s[index] == '('

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

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…