Multiply Two Polynomials - Problem

You are given two integer arrays poly1 and poly2, where the element at index i in each array represents the coefficient of xi in a polynomial.

Let A(x) and B(x) be the polynomials represented by poly1 and poly2, respectively.

Return an integer array result of length (poly1.length + poly2.length - 1) representing the coefficients of the product polynomial R(x) = A(x) * B(x), where result[i] denotes the coefficient of xi in R(x).

Input & Output

Example 1 — Basic Multiplication
$ Input: poly1 = [1,2], poly2 = [3,4]
Output: [3,10,8]
💡 Note: Polynomial A(x) = 1 + 2x, B(x) = 3 + 4x. A(x) * B(x) = (1)(3) + (1)(4x) + (2x)(3) + (2x)(4x) = 3 + 4x + 6x + 8x² = 3 + 10x + 8x²
Example 2 — Single Coefficients
$ Input: poly1 = [1,2,1], poly2 = [2]
Output: [2,4,2]
💡 Note: A(x) = 1 + 2x + x², B(x) = 2. A(x) * B(x) = 2(1 + 2x + x²) = 2 + 4x + 2x²
Example 3 — Zero Coefficients
$ Input: poly1 = [1,0,1], poly2 = [1,1]
Output: [1,1,1,1]
💡 Note: A(x) = 1 + 0x + x² = 1 + x², B(x) = 1 + x. A(x) * B(x) = (1 + x²)(1 + x) = 1 + x + x² + x³

Constraints

  • 1 ≤ poly1.length, poly2.length ≤ 100
  • -100 ≤ poly1[i], poly2[i] ≤ 100

Visualization

Tap to expand
Multiply Two Polynomials INPUT A(x) = poly1 1 x^0 2 x^1 A(x) = 1 + 2x B(x) = poly2 3 x^0 4 x^1 B(x) = 3 + 4x poly1 = [1, 2] poly2 = [3, 4] ALGORITHM STEPS 1 Initialize Result result[3] = [0, 0, 0] 2 Nested Loop For each i,j pair 3 Accumulate result[i+j] += p1[i]*p2[j] 4 Return Result Polynomial product Coefficient Accumulation: i=0,j=0: r[0] += 1*3 = 3 i=0,j=1: r[1] += 1*4 = 4 i=1,j=0: r[1] += 2*3 = 10 i=1,j=1: r[2] += 2*4 = 8 result = [3, 10, 8] FINAL RESULT R(x) = A(x) * B(x) 3 x^0 10 x^1 8 x^2 R(x) = 3 + 10x + 8x² Verification: (1 + 2x)(3 + 4x) = 3 + 4x + 6x + 8x² = 3 + 10x + 8x² Output: [3, 10, 8] OK - Verified! Key Insight: When multiplying polynomials, the coefficient of x^k in the result comes from all pairs (i, j) where i + j = k. Direct accumulation: result[i+j] += poly1[i] * poly2[j] achieves O(n*m) time complexity. TutorialsPoint - Multiply Two Polynomials | Direct Coefficient Accumulation
Asked in
Google 15 Facebook 12 Microsoft 8
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen