Parse, Normalize, and Combine Polynomials
Learn this problemProblem statement
You are given one or more valid single-variable polynomial strings in polynomials. Each expression contains no whitespace and is a sequence of signed terms. A term is a decimal integer constant or a decimal coefficient followed by x and an optional nonnegative exponent, such as -7, x, -3x, or 12x^4. An omitted coefficient is 1, and an omitted exponent is 1.
Add all input polynomials and return one canonical string. Collect equal exponents, omit zero terms, order terms by decreasing exponent, omit coefficient 1 and -1 on nonconstant terms, and use normalized signs without whitespace. Return 0 when every term cancels.
Every parsed signed coefficient and every intermediate combined coefficient must fit in a signed 64-bit integer. Return exactly OVERFLOW as soon as either a parsed coefficient or an addition is outside that range.
Function
combinePolynomials(polynomials: String[]) → StringExamples
Example 1
polynomials = ["3x^2-x+4","-x^2+5x-4"]return = "2x^2+4x"Like powers are added and zero constant terms disappear.
Example 2
polynomials = ["x^3-x","-x^3+x"]return = "0"Every coefficient cancels, so the canonical representation is zero.
Example 3
polynomials = ["9223372036854775807","1"]return = "OVERFLOW"Adding the constants would exceed the signed 64-bit maximum.
Constraints
1 <= polynomials.length <= 200.- Every expression is valid under the grammar above and has length from
1through2000. - Coefficient magnitudes contain at most
20decimal digits. - Every exponent is from
0through10^6.