Nishant AP 1.2
Nishant AP 1.2
Experiment 2
TASK – 2.1
1. Aim: You have three stacks of cylinders where each cylinder has the same
diameter, but they may vary in height. You can change the height of a stack by
removing and discarding its topmost cylinder any number of times.
Find the maximum possible height of the stacks such that all of the stacks are
exactly the same height. This means you must remove zero or more cylinders
from the top of zero or more of the three stacks until they are all the same height,
then return the height.
2. Script:
int equalStacks(vector<int> h1, vector<int> h2, vector<int> h3) {
stack<int> stk1;
stack<int> stk2;
stack<int> stk3;
int sum1=0,sum2=0,sum3=0;
for(int i=h1.size()-1;i>=0;i--){
sum1=sum1+h1[i];
stk1.push(sum1);
}
for(int i=h2.size()-1;i>=0;i--){
3. OUTPUT
TASK – 2.2
1. Aim: A bracket is considered to be any one of the following characters: (, ), {, }, [, or
]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or
{) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are
three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not
balanced if the set of brackets it encloses are not matched. For example, {[(])} is not
balanced because the contents in between { and } are not balanced. The pair of square
brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses
encloses a single, unbalanced closing square bracket, ].
By this logic, we say a sequence of brackets is balanced if the following conditions are
met:
i. It contains no unmatched brackets.
ii. The subset of brackets enclosed within the confines of a matched pair of brackets
is also a matched pair of brackets.
iii. Given strings of brackets, determine whether each sequence of brackets is
balanced. If a string is balanced, return YES. Otherwise, return NO.
2. Script:
string isBalanced(string s) {
stack<char>bracketsStack;
int length=s.size();
int i;
for(i=0;i<length;i++){
if((s[i]=='{') || (s[i]=='(') || (s[i]=='[')){
bracketsStack.push(s[i]);
}
else if(bracketsStack.empty()){
break;
}
else if(bracketsStack.top()=='{' && s[i]=='}'){
bracketsStack.pop();
}
else if(bracketsStack.top()=='(' && s[i]==')'){
UID: 21BCS7081 Name: Nishant Bhardwaj
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
bracketsStack.pop();
}
else if(bracketsStack.top()=='[' && s[i]==']'){
bracketsStack.pop();
}
else{
break;
}
}
if(i==length && bracketsStack.empty()){
return "YES";
}
else{
return "NO";
}
}
3. OUTPUT