FastPrepSimplify a Quadratic Expression

Simplify a Quadratic Expression

OpenAI logoOpenAI● MediumFULLTIMEOA
Learn

Problem statement

Given a valid string polynom representing a quadratic expression, combine like terms and return the final coefficients.

The expression is a sum of terms in any order. Each term is one of:

  • a constant such as 4 or -12;
  • a linear term such as 5x, -x, or +x;
  • a quadratic term such as 7x^2, -x^2, or +x^2.

A missing coefficient before x means 1. Return an array [a, b, c], where the simplified expression is ax^2 + bx + c.

Function

simplifyQuadratic(polynom: String) → int[]

Examples

Example 1

polynom = "5x+7x^2+4+x^2-24x"return = [8,-19,4]

The quadratic coefficient is 7 + 1 = 8, the linear coefficient is 5 - 24 = -19, and the constant is 4.

Example 2

polynom = "x^2-x+1"return = [1,-1,1]

The omitted coefficients of x^2 and -x are 1 and -1.

Example 3

polynom = "-3+2x^2+3-2x^2"return = [0,0,0]

Both the quadratic terms and the constant terms cancel.

Constraints

  • 1 <= polynom.length <= 100000.
  • polynom contains no spaces and is a valid sequence of signed constant, x, and x^2 terms.
  • Every explicit coefficient is a base-10 integer.
  • The final three coefficients fit in a signed 32-bit integer.

More OpenAI problems

See OpenAI hiring insights
public int[] simplifyQuadratic(String polynom) {
    // Write your code here.
}
polynom"5x+7x^2+4+x^2-24x"
expected[8,-19,4]
Checking account…