Find the Cow
InterviewTime limit1sMemory limit128 MB
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 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 is the index where an (( begins and is the index where a )) begins, then a spot where Bessie could be standing is an ordered pair with .
Help John by counting the number of distinct ordered pairs where Bessie could be standing.
Input
The first line contains a string of length consisting only of parentheses. ()
Output
Print the number of spots where Bessie could stand — that is, the number of distinct ordered pairs where is the starting index of an (( and is the starting index of a )) with .
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 .