Explore
Placement Prep

Edit

Edit

# Opening and closing gates problem | Algorithm to find whether people are safe or not

Published on 09 Mar 2020

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 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.

## Solution to opening and closing gates problem

This question was asked in the recruitment drive of companies like Wipro.


C
C++
Java
Python 3

Output
Input- Enter the String: () ((())) () Output- 5 Input- Enter the string () () (()) Output- 4

Recommended Programs