Skip to content

Commit 80d5d72

Browse files
committed
balanced-parenthesis
1 parent bd15e6e commit 80d5d72

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
2222
- [Implement Queue Using Stack](src/_DataStructures_/Stack/immitate-queue-using-stack)
2323
- [Baseball Game](src/_DataStructures_/Stack/baseball-game)
2424
- [Minimum Stack](src/_DataStructures_/Stack/min-stack)
25+
- [Balanced Parenthesis](src/_DataStructures_/Stack/balanced-parenthesis)
26+
2527
- [Queue](src/_DataStructures_/Queue)
2628
- [Weave](src/_DataStructures_/Queue/weave)
2729

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
Given an expression string exp , write a program to examine whether the pairs and
3+
the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in expression.
4+
5+
Example:
6+
Input: exp = “[()]{}{[()()]()}”
7+
Output: true
8+
9+
Input: exp = “[(])”
10+
Output: false
11+
*/
12+
13+
14+
const Stack = require('../index');
15+
16+
function checkBalancedParenthesis(expression) {
17+
let s = new Stack();
18+
for (let i = 0; i < expression.length; i++) {
19+
const char = expression[i];
20+
if (char === '{' || char === '(' || char === '[') {
21+
//If current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack
22+
s.push(char);
23+
} else {
24+
if (s.isEmpty()) {
25+
//when we have only right parenthesis or brackets in expresion
26+
return false;
27+
} else if (char === '}' && s.peek() !== '{' || char === ')' && s.peek() !== '(' || char === ']' && s.peek() !== '[') {
28+
return false;
29+
}
30+
//If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop it from stack
31+
s.pop();
32+
}
33+
}
34+
if (s.isEmpty()) {
35+
//expression has balanced parenthesis
36+
return true;
37+
} else {
38+
return false;
39+
}
40+
}
41+
42+
console.log(checkBalancedParenthesis("{()}[]")); //true
43+
console.log(checkBalancedParenthesis("{()}}")); //false

src/_DataStructures_/Stack/index.js

+3
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ class Stack {
1515
peek() {
1616
return this.data[this.data.length - 1];
1717
}
18+
isEmpty(){ //check if stack is empty
19+
return this.data.length==0;
20+
}
1821
}
1922

2023
module.exports = Stack;

0 commit comments

Comments
 (0)