1197. Polynomial Tidy-Up

Medium3.5 points estimatedStringHash TableSorting

A homework helper must simplify sums of terms in x such as 3x^2 - x + 4 - x^2 + 2x. Each term is an optional sign, an optional coefficient, and optionally x with an optional ^power; a missing coefficient means 1, a bare x means power 1, and no x means power 0. Spaces may appear anywhere except inside a number.

Combine like powers and return the canonical form: terms in descending power, zero terms dropped, a coefficient of 1 omitted except for the constant, x for power 1, terms joined by " + " or " - ", and a leading - (no space) if the first term is negative. If everything cancels return "0".

Parsing once and keeping an array of 101 coefficients takes O(n) time and O(1) space.

Example 1

Input:
expr = "3x^2 - x + 4 - x^2 + 2x"
Output:
"2x^2 + x + 4"
Explanation:

Like powers combine: 3x^2 - x^2 = 2x^2, -x + 2x = x, and the constant is 4.

Example 2

Input:
expr = "x - x"
Output:
"0"
Explanation:

The terms cancel, so the answer is 0.

Example 3

Input:
expr = "-2x^3 + 5 - 3x^3"
Output:
"-5x^3 + 5"
Explanation:

The cubic terms combine to -5x^3 and the constant stays 5.

Constraints

1 ≤ expr.length ≤ 1000

powers are 0 to 100

|coefficient| ≤ 106, combined coefficients fit in an int

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…