Skip to content

Commit 6d0c0c7

Browse files
authored
Update balanced-paranthesis.js
1 parent 642306e commit 6d0c0c7

File tree

1 file changed

+16
-30
lines changed

1 file changed

+16
-30
lines changed

balanced-paranthesis.js

+16-30
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,24 @@
1-
const frequency = (string, character) => {
2-
return string.split("").reduce((count, c) => {
3-
return count + (c == character ? 1 : 0);
4-
}, 0);
5-
};
6-
7-
const validParantheses = (N, store = "") => {
8-
const openBracketCount = frequency(store, "(");
9-
const closedBracketCount = frequency(store, ")");
10-
1+
const balancedParanthesis = (N, paranthesis = [], openCount, closedCount) => {
112
if (
12-
openBracketCount > N ||
13-
closedBracketCount > N ||
14-
closedBracketCount > openBracketCount
3+
closedCount > openCount ||
4+
paranthesis.length > 2 * N ||
5+
openCount > N ||
6+
closedCount > N
157
) {
168
return;
179
}
18-
19-
if (store.length === 2 * N) {
20-
console.log(store);
10+
if (paranthesis.length === 2 * N) {
11+
console.log(paranthesis.join(""));
2112
return;
22-
} else {
23-
validParantheses(N, store + "(");
24-
validParantheses(N, store + ")");
2513
}
14+
15+
paranthesis = paranthesis.concat("(");
16+
balancedParanthesis(N, paranthesis, openCount + 1, closedCount);
17+
paranthesis = paranthesis.slice(0, paranthesis.length - 1);
18+
paranthesis = paranthesis.concat(")");
19+
balancedParanthesis(N, paranthesis, openCount, closedCount + 1);
2620
};
2721

28-
let count = 0,
29-
calls = 0;
30-
console.log(validParantheses(3, ""));
31-
console.log(count, calls);
32-
/*
33-
Parantheses Conditions
34-
1) Open < Count/2
35-
2) Closed < Count/2
36-
3) Open >= Closed
37-
4) Open === Closed return;
38-
*/
22+
const N = 3;
23+
balancedParanthesis(N, [], 0, 0);
24+

0 commit comments

Comments
 (0)