- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 56 lines of C++ from the credited upstream file 1634.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/**2 * Definition for polynomial singly-linked list.3 * struct PolyNode {4 * int coefficient, power;5 * PolyNode *next;6 * PolyNode(): coefficient(0), power(0), next(nullptr) {};7 * PolyNode(int x, int y): coefficient(x), power(y), next(nullptr) {};8 * PolyNode(int x, int y, PolyNode* next): coefficient(x), power(y),9 * next(next) {};10 * };11 */12 13class Solution {14 public:15 PolyNode* addPoly(PolyNode* poly1, PolyNode* poly2) {16 PolyNode* dummy = new PolyNode();17 PolyNode* curr = dummy;18 PolyNode* p = poly1; 19 PolyNode* q = poly2; 20 21 while (p != nullptr && q != nullptr) {22 if (p->power > q->power) {23 curr->next = new PolyNode(p->coefficient, p->power);24 curr = curr->next;25 p = p->next;26 } else if (p->power < q->power) {27 curr->next = new PolyNode(q->coefficient, q->power);28 curr = curr->next;29 q = q->next;30 } else { 31 const int sumCoefficient = p->coefficient + q->coefficient;32 if (sumCoefficient != 0) {33 curr->next = new PolyNode(sumCoefficient, p->power);34 curr = curr->next;35 }36 p = p->next;37 q = q->next;38 }39 }40 41 while (p != nullptr) {42 curr->next = new PolyNode(p->coefficient, p->power);43 curr = curr->next;44 p = p->next;45 }46 47 while (q != nullptr) {48 curr->next = new PolyNode(q->coefficient, q->power);49 curr = curr->next;50 q = q->next;51 }52 53 return dummy->next;54 }55};56