forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveOuterParenthesis.js
40 lines (34 loc) · 1014 Bytes
/
RemoveOuterParenthesis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const removeOuterParenthesis = (str) => {
// breaking the string into an array of characters
let strArr = str.split('');
let stack=[];
// looping the array to check the characters
for(let i = 0; i < strArr.length; i++){
// we store the index if the character is an opening parenthesis
if(strArr[i] == '(') {
stack.push(i);
} else {
// removing the elements of stack
let ele = stack.pop();
// this checks if we have reached the outermost
// closing parenthesis
if(!stack.length){
// replace the outermost characters with 0
strArr[i] = '0';
strArr[ele] = '0';
}
}
}
// return the string after removing the 0's and joining the characters
return strArr.filter(x=>x!='0').join('');
}
console.log(removeOuterParenthesis("(()())(())"));
console.log(removeOuterParenthesis("(()())(())(()(()))"));
/**
* Output for the above inputs:
* ()()()
* ()()()()(())
*
* Time complexity: O(n)
* Space complexity: O(n)
*/