624. Add Two Polynomials Represented as Linked Lists

Given two polynomials represented as linked lists. Each node contains a coefficient and an exponent, where:

  • cofficient is an integer.
  • exponent is a positive integer and denotes the power of the variable x.

Write a function to add the two polynomials and return the result as a linked list in descending order of exponents.

Example 1:

Input: poly1 = [[3,4],[2,2],[1,0]], poly2 = [[4,3],[3,1],[2,0]]

Output: [[3,4],[4,3],[2,2],[3,1],[3,0]]

Explanation:

poly1: 3x⁴ + 2x² + 1

poly2: 4x³ + 3x + 2

Sum: 3x⁴ + 4x³ + 2x² + 3x + 3

Example 2:

Input: poly1 = [[1,3],[2,2]], poly2 = [[3,3],[4,2]]

Output: [[4,3],[6,2]]

Explanation:

poly1: x³ + 2x²

poly2: 3x³ + 4x²

Sum: 4x³ + 6x²

Now Your Turn!

Pick the correct output for the given input

Input: poly1 = [[2,2],[4,1],[3,0]], poly2 = [[3,2],[-4,1],[-1,0]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= n <= 10⁴
  • -10⁹ <= PolyNode.coefficient <= 10⁹
  • PolyNode.coefficient ≠ 0
  • 0 <= PolyNode.power <= 10⁹
  • PolyNode.power > PolyNode.next.power

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for polynomial singly-linked list.
* struct PolyNode {
* int coefficient, power;
* PolyNode *next;
* PolyNode(): coefficient(0), power(0), next(nullptr) {};
* PolyNode(int x, int y): coefficient(x), power(y), next(nullptr) {};
* PolyNode(int x, int y, PolyNode* next): coefficient(x), power(y), next(next) {};
*};
*/
 
class Solution {
public:
PolyNode* addPoly(PolyNode* poly1, PolyNode* poly2) {
// Your Code Goes Here
}
};
Test Case

Input:

Poly1
Poly2