Not the answer:
function PolynomialExpansion(str) { // multiply to polynomial expressions const multiply = (a, b) => { const variableA = a.match(/[a-zA-Z]\^/i); const [coefficientA, exponentA] = a.split(/[a-zA-Z]\^/i); const [coefficientB, exponentB] = b.split(/[a-zA-Z]\^/i); let newCoefficient; if (coefficientA !== '' && coefficientB !== '') { newCoefficient = parseInt(coefficientA) * parseInt(coefficientB); } else if (coefficientA !== '') { newCoefficient = parseInt(coefficientA); } else { newCoefficient = parseInt(coefficientB); } let newExponent; if (exponentA !== '' && exponentB !== '') { newExponent = parseInt(exponentA) + parseInt(exponentB); } else if (exponentA !== '') { newExponent = parseInt(exponentA); } else { newExponent = parseInt(exponentB); } return `${newCoefficient}${variableA ? variableA[0] : ''}${newExponent}`; }; const matches = str.match(/\(.*?\)/gi); if (!matches) { return; } const [a, b] = matches.map(el => el.replace('(', '').replace(')', '')); let firstEl = a.split(/[+-]/gi); let secondEl = b.split(/[+-]/gi); let resArr = []; for (let i = 0; i < firstEl.length; i++) { for (let j = 0; j < secondEl.length; j++) { resArr.push(multiply(firstEl[i], secondEl[j])); } } console.log(resArr); // code goes here return str; } // keep this function call here d console.log(PolynomialExpansion(readline()));