Find the Cow

Interview

Time limit1sMemory limit128 MB

Summary
Count ordered pairs of indices (x, y) with x < y where an "((" starts at x and a "))" starts at y in a parenthesis string.
Level

Easy3 of 10

Topics
String, Prefix sum, Implementation, Array
Solved
No attempts yet

Problem

The reckless calf Bessie (age 1) has escaped the barn and hidden on a grassy hillside. Farmer John searched every clump of grass but could not find her, because to John the field looks like a string of NN parentheses. For example:

)((()())())

John knows that Bessie's two hind legs look exactly like two adjacent opening parentheses ((, and her two front legs look exactly like two adjacent closing parentheses )). If xx is the index where an (( begins and yy is the index where a )) begins, then a spot where Bessie could be standing is an ordered pair (x,y)(x, y) with x<yx < y.

Help John by counting the number of distinct ordered pairs (x,y)(x, y) where Bessie could be standing.

Input

The first line contains a string of length NN consisting only of parentheses. (1≤N≤50,0001 \le N \le 50{,}000)

Output

Print the number of spots where Bessie could stand — that is, the number of distinct ordered pairs (x,y)(x, y) where xx is the starting index of an (( and yy is the starting index of a )) with x<yx < y.

Hint

For the string )((()())()), the (( patterns begin at indices 1 and 2, and the )) patterns begin at indices 6 and 9 (0-indexed). Every (( comes before every )), so the number of valid pairs is 2×2=42 \times 2 = 4.

Examples2

  1. Example 1

    Input
    )((()())())
    
    Expected output
    4
    
  2. Example 2

    Input
    (())
    
    Expected output
    1