PROBLEM LINK:
Contest Division 1
Contest Division 2
Contest Division 3
Contest Division 4
Setter: Utkarsh Gupta
Tester: Nishank Suresh, Utkarsh Gupta
Editorialist: Pratiyush Mishra
DIFFICULTY:
1472
PREREQUISITES:
Strings
PROBLEM:
A bracket sequence S is called dense if one of the following is true:
- S is empty.
- S = (X) where X is dense.
You are given a bracket sequence S. What is the minimum number of brackets you must remove to make it dense?
EXPLANATION:
In order to solve this problem we can keep a count of all the opening brackets and closing brackets for each position in the string. First we will calculate the number of closing brackets in the string. This would be denoted by close
The maximum answer can be n as we would get a dense string if we remove all the brackets. Now we traverse from 1 to n. Initially we would have 0 opening brackets(denoted by open) and close closing brackets. At each position there can be two cases:
- s[i] = (: Here we increment open by 1. Thus we have open opening brackets in the left and close closing brackets at the right, so the maximum length of dense string that can be formed at this position is min(2 \times open, 2 \times close). Thus,
- s[i] = ): Here we simply decrement close by 1.
By the end of our traversal we will have our answer.
TIME COMPLEXITY:
O(N), for each test case.
SOLUTION:
Editorialistâs Solution
Setterâs Solution
Tester1âs Solution
Tester2âs Solution