Polynomial Addition - Problem

Given two polynomials represented as linked lists, implement polynomial addition and return the result as a linked list.

Each node in the linked list contains:

  • coeff: coefficient of the term
  • exp: exponent of the term
  • next: pointer to next node

The polynomials are sorted in descending order of exponents.

Example: For polynomials 3x² + 5x + 2 and 4x² + 2x + 1, the result should be 7x² + 7x + 3.

Input & Output

Example 1 — Basic Addition
$ Input: poly1 = [[3,2],[5,1],[2,0]], poly2 = [[4,2],[2,1],[1,0]]
Output: [[7,2],[7,1],[3,0]]
💡 Note: Adding polynomials 3x² + 5x + 2 and 4x² + 2x + 1: coefficients with same exponents are added (3+4=7, 5+2=7, 2+1=3)
Example 2 — Different Exponents
$ Input: poly1 = [[1,3],[4,1]], poly2 = [[2,2],[3,1]]
Output: [[1,3],[2,2],[7,1]]
💡 Note: Adding x³ + 4x and 2x² + 3x: x³ and 2x² have no matching terms, x terms combine (4+3=7)
Example 3 — Coefficient Cancellation
$ Input: poly1 = [[5,2],[3,1]], poly2 = [[-5,2],[2,0]]
Output: [[3,1],[2,0]]
💡 Note: Adding 5x² + 3x and -5x² + 2: the x² terms cancel out (5-5=0), leaving 3x + 2

Constraints

  • 1 ≤ length of polynomial ≤ 100
  • -1000 ≤ coefficient ≤ 1000
  • 0 ≤ exponent ≤ 100
  • Polynomials are sorted in descending order by exponent

Visualization

Tap to expand
INPUTALGORITHMRESULT3x²5x¹2x⁰First Polynomial4x²2x¹1x⁰Second Polynomial1Compare exponents atcurrent pointer positions2If equal: add coefficientsIf different: copy higher exp3Advance pointer(s) andrepeat until both doneTwo-Pointer MergeTime: O(n+m)7x²7x¹3x⁰Combined Polynomial3+4=7, 5+2=7, 2+1=37x² + 7x + 3Key Insight:Polynomial addition is like merging two sorted lists - compare exponentsand combine coefficients for matching powers, maintaining sorted order.TutorialsPoint - Polynomial Addition | Two-Pointer Merge
Asked in
Microsoft 15 Adobe 12 Samsung 8
8.5K Views
Medium Frequency
~25 min Avg. Time
340 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