Add Two Polynomials Represented as Linked Lists - Problem

A polynomial linked list is a special type of linked list where every node represents a term in a polynomial expression.

Each node has three attributes:

  • coefficient: an integer representing the number multiplier of the term. The coefficient of the term 9x⁴ is 9.
  • power: an integer representing the exponent. The power of the term 9x⁴ is 4.
  • next: a pointer to the next node in the list, or null if it is the last node of the list.

For example, the polynomial 5x³ + 4x - 7 is represented by the polynomial linked list with nodes [[5,3],[4,1],[-7,0]].

The polynomial linked list must be in its standard form:

  • The polynomial must be in strictly descending order by its power value.
  • Terms with a coefficient of 0 are omitted.

Given two polynomial linked list heads, poly1 and poly2, add the polynomials together and return the head of the sum of the polynomials.

PolyNode format: The input/output format is as a list of n nodes, where each node is represented as its [coefficient, power]. For example, the polynomial 5x³ + 4x - 7 would be represented as: [[5,3],[4,1],[-7,0]].

Input & Output

Example 1 — Basic Addition
$ Input: poly1 = [[1,2],[2,1]], poly2 = [[6,2],[4,1]]
Output: [[7,2],[6,1]]
💡 Note: Both polynomials have terms with powers 2 and 1. For power 2: 1 + 6 = 7. For power 1: 2 + 4 = 6. Result is 7x² + 6x.
Example 2 — Different Powers
$ Input: poly1 = [[1,3]], poly2 = [[1,2],[1,1]]
Output: [[1,3],[1,2],[1,1]]
💡 Note: No common powers, so all terms appear in the result: x³ + x² + x.
Example 3 — Coefficients Cancel Out
$ Input: poly1 = [[2,2],[3,1]], poly2 = [[-2,2],[1,0]]
Output: [[3,1],[1,0]]
💡 Note: Power 2 terms cancel: 2 + (-2) = 0, so only 3x + 1 remains.

Constraints

  • 0 ≤ m, n ≤ 104
  • -109 ≤ poly1[i].coefficient, poly2[i].coefficient ≤ 109
  • poly1[i].power > poly1[i+1].power
  • poly2[i].power > poly2[i+1].power

Visualization

Tap to expand
Polynomial Addition: Combine Like TermsPoly1: x² + 2x[1,2][2,1]Poly2: 6x² + 4x[6,2][4,1]Add coefficients of same powers:x²: 1 + 6 = 7x¹: 2 + 4 = 6Result: 7x² + 6x[7,2][6,1]
Understanding the Visualization
1
Input
Two polynomials represented as linked lists in descending power order
2
Process
Add coefficients of terms with same power, keep unique terms
3
Output
New polynomial with combined terms in descending power order
Key Takeaway
🎯 Key Insight: Use two pointers to merge polynomials like sorted lists, comparing powers and combining coefficients
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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