Best in JAVA Solution with T.C. => O(N) using Stack; By : Shashank ;

interview-questions
amazon
google
Tags: #<Tag:0x00007f241f7af130> #<Tag:0x00007f241f7aeff0> #<Tag:0x00007f241f7aeeb0>

#1

int n=A.length();
if(n == 1) return 0;
if(A.isEmpty()) return 1;
Stackstack=new Stack<>();
for(int i=0;i<n;i++){
if(A.charAt(i)==’(’){
stack.push(A.charAt(i));
}else if(A.charAt(i)==’)’ && !stack.isEmpty()){
if(stack.peek()==’(’) stack.pop();
else return 0;
}else if(A.charAt(i)==’)’ && stack.isEmpty()) return 0;
}
if(stack.isEmpty()) return 1;
else if(stack.peek()==’)’ || stack.peek()==’(’) return 0;
return 0;
Done By : Shashank ;