Add Two Polynomials Represented as Linked Lists - Problem

Imagine you're working with polynomial expressions like 5x³ + 4x - 7, but instead of storing them as strings, you represent them using linked lists where each node contains a coefficient and power.

A polynomial linked list is a special data structure where:

  • coefficient: The number multiplier (e.g., in 9x⁴, coefficient = 9)
  • power: The exponent (e.g., in 9x⁴, power = 4)
  • next: Pointer to the next term

The polynomial 5x³ + 4x - 7 would be represented as: [[5,3], [4,1], [-7,0]]

Rules:

  • Terms must be in strictly descending order by power
  • Terms with coefficient 0 are omitted
  • Standard mathematical form is maintained

Your task: Given two polynomial linked lists poly1 and poly2, add them together and return the head of the resulting polynomial in proper form.

Input & Output

example_1.py — Basic Addition
$ Input: poly1 = [[1,1]], poly2 = [[1,0]]
Output: [[1,1],[1,0]]
💡 Note: Adding x + 1 gives us x + 1. Since the powers are different (1 and 0), we keep both terms in descending order.
example_2.py — Combining Like Terms
$ Input: poly1 = [[2,2],[4,1],[3,0]], poly2 = [[3,2],[-4,1],[-1,0]]
Output: [[5,2],[2,0]]
💡 Note: Adding (2x² + 4x + 3) + (3x² - 4x - 1) = 5x² + 2. The x terms cancel out (4x - 4x = 0) and are omitted.
example_3.py — Complete Cancellation
$ Input: poly1 = [[1,2]], poly2 = [[-1,2]]
Output: []
💡 Note: Adding x² + (-x²) = 0. Since the result has no non-zero terms, we return an empty polynomial.

Constraints

  • 0 ≤ m, n ≤ 104 where m and n are the lengths of poly1 and poly2
  • -109 ≤ coefficient ≤ 109
  • 0 ≤ power ≤ 109
  • Both polynomials are in descending order by power
  • No terms have coefficient 0 in the input

Visualization

Tap to expand
Recipe 1: 5x³ + 4x - 75x³4x-7Recipe 2: 3x³ + 2x²3x³2x²Combined Recipe Result8x³2x²4x-75x³ + 3x³ = 8x³Add remaining terms
Understanding the Visualization
1
Set Up Recipe Cards
Place both polynomial recipes side by side, each sorted by ingredient complexity
2
Compare Current Ingredients
Look at the current ingredient from each recipe and compare their types (powers)
3
Combine or Choose
If ingredients match, add their amounts; otherwise take the more complex ingredient
4
Move to Next
Advance to the next ingredient in the appropriate recipe(s)
5
Finish Remaining
Add any remaining ingredients from the non-empty recipe
Key Takeaway
🎯 Key Insight: Since both polynomials are pre-sorted by power, we can merge them in one pass like merging sorted arrays, achieving optimal O(m + n) time complexity.
Asked in
Google 28 Amazon 22 Microsoft 18 Meta 15
24.0K Views
Medium Frequency
~18 min Avg. Time
850 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