#K61972. Find the Corresponding Closing Parenthesis

    ID: 31428 Type: Default 1000ms 256MiB

Find the Corresponding Closing Parenthesis

Find the Corresponding Closing Parenthesis

Given a string ( s ) consisting only of the characters '(' and ')', and an index of an opening parenthesis, your task is to find the index of the corresponding closing parenthesis. The matching is determined by the usual rule: every opening parenthesis must be paired with the correct closing parenthesis following a balanced structure. Specifically, if you are given an index ( i ) such that ( s[i] = ( ), you need to return the index ( j ) such that ( s[j] = ) ) and the substring ( s[i...j] ) is a balanced sequence. If the input index is invalid or no matching closing parenthesis exists, return (-1).

Examples:
1. For ( s = "(()(()))" ) and index ( 0 ), the answer is ( 7 ).
2. For ( s = "(()(()))" ) and index ( 1 ), the answer is ( 2 ).
3. For ( s = "((())" ) and index ( 0 ), the answer is (-1).

inputFormat

Input is read from standard input (stdin). The first line contains a string ( s ) consisting solely of the characters '(' and ')'. The second line contains an integer representing the 0-based index of the opening parenthesis whose matching closing parenthesis you need to find.

outputFormat

Output a single integer to standard output (stdout), which is the index of the corresponding closing parenthesis. If no valid closing parenthesis exists, output (-1).## sample

(()(()))
0
7

</p>