Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/_Problems_/balanced-parentheses.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const { parentheses } = require('.');

describe('Parentheses', () => {
it('Should return true only when matching brackets are there', () => {
expect(parentheses("{[()]})").toEqual('Balanced');
});

it('Should return false when matching brackets are not there', () => {
expect(parentheses("{[()}])").toEqual('UnBalanced');
});
it('Should return true only when matching brackets are there', () => {
expect(parentheses("{()})").toEqual('Balanced');
});

it('Should return false when matching brackets are not there', () => {
expect(parentheses("{[}])").toEqual('UnBalanced');
});



});
36 changes: 36 additions & 0 deletions src/_Problems_/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// FIND BALANCED PARENTHESIS
// FOR '[{()}]' ---->>>> BALANCED
// FOR '[{()]' ---->>>> UNBALANCED
// Time complexity : O(n) n is the length of the string provided.


function parentheses(s) {
if(typeof s !== "string" || s.length % 2 !== 0) return false;
let i = 0;
let arr = [];
while(i<s.length) {
if(s[i]=== "{" || s[i]=== "(" || s[i]=== "[") {
arr.push(s[i]);
}
else if(s[i] === "}" && arr[arr.length-1] === "{") {
arr.pop();
}
else if(s[i] === ")" && arr[arr.length-1] === "(") {
arr.pop();
}
else if(s[i] === "]" && arr[arr.length-1] === "[") {
arr.pop();
}
return "Unbalanced";

i++
}
if (arr.length === 0)
return "Balanced";
};



module.exports = {
parentheses,
};