A water reservation system constructed in a city has several opening and closing gates. If any opening gates are not closed with a corresponding closing gate then the water will leak out of the system and there will be a threat to the life of people living in the city. Also, the closing gate cannot exist without the opening gate, so the system head checks the design of the system and he has to ensure that the people are safe in the city. Write an algorithm to find out whether people are safe or not.
Input:
The input to the function/method consists of one argument – str, a string representing the sequence of gates of the water reservation system.
Output:
Return an integer representing the number of gates which have closing gates corresponding to the opening gates else return an integer -1.
Constraints:
The opening gates are represented by ‘(‘ and closing gates are represented by ‘)’
Example 1
Input: Str = ()()
Output: 2
Logic:
This problem is like the balanced parenthesis problem. Once a pair of parenthesis is found (the pair should have an opening parenthesis and closing parenthesis), a counter is incremented.
This question was asked in the recruitment drive of companies like Wipro.n
@@coding::1@@
Recommended Programs