function solution(p) {
if(p === '') return '';
let answer = '';
let open = 0;
let close = 0;
let checkCorrect = true;
for(let i = 0; i < p.length; i++) {
p.slice(i,i+1) == '(' ? open++ : close++
if(close > open) checkCorrect = false
if(open === close) {
if(checkCorrect) {
answer += p.slice(0,i+1);
answer += solution(p.slice(i+1));
return answer;
} else {
answer += `(${solution(p.slice(i+1))})`;
for (let j = 1; j < i; j++) {
answer += p[j] == '(' ? ')' : '(';
}
return answer;
}
}
}
}