Polynomial Addition | Practice | GeeksforGeeks

Given two polynomial numbers represented by a linked list. The task is to complete the function addPolynomial() that adds these lists meaning adds the coefficients who have the same variable powers.
Note:  Given polynomials are sorted in decreasing order of power.
Example 1:
Input:
LinkedList1:  (1,x2) 
LinkedList2:  (1,x3)
Output:
1x^3 + 1x^2
Explanation: Since, x2 and x3 both have
different powers as 2 and 3. So, their
coefficient can't be added up.

Example 2:
Input:
LinkedList1:  (1,x3) -> (2,x2)
LinkedList2:  (3,x3) -> (4,x2)
Output:
4x^3 + 6x^2
Explanation: Since, x3 has two different
coefficients as 3 and 1. Adding them up
will lead to 4x3. Also, x2 has two
coefficients as 4 and 2. So, adding them
up will give 6x2.
Your Task:
The task is to complete the function addPolynomial() which should add the polynomial with same powers return the required polynomial in decreasing order of the power in the form of a linked list.
Note: Try to solve the question without using any extra space.
Expected Time Complexity: O(N+M)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N, M <= 105
1 <= x, y <= 106
0
tthakare733 days ago
//java Solution -> TC -> 0.4
class Solution{
    static Node Result, dummy;
    
    public static void createResult(int coff, int pow){
        Node newNode = new Node(coff, pow);
        if(Result == null) {
            Result = newNode;
            dummy = Result;
        } else {
            dummy.next = newNode;
            dummy = dummy.next;
        }
    }
    
    public static Node addPolynomial(Node p1,Node p2){
        Result = null;
        dummy  = null;
        while(p1 != null && p2 != null){
            if(p1.pow == p2.pow){
                createResult(p1.coeff+p2.coeff, p1.pow);
                p1 = p1.next;
                p2 = p2.next;
            } else {
                if(p1.pow > p2.pow){
                    createResult(p1.coeff, p1.pow);
                    p1 = p1.next;
                } else {
                    createResult(p2.coeff, p2.pow);
                    p2 = p2.next;
                }
            }
        }
        return Result;
    }
}
0
gupta2411sumit2 weeks ago
public static Node addPolynomial(Node p1,Node p2)   {       //Add your code here.       Node i = p1 ;       Node j = p2 ;       Node k = new Node(0 , 0 )  ;       Node ans = k ;              while(i != null && j != null)       {           if(i.pow==j.pow)           {               k.next = new Node( i.coeff+j.coeff , i.pow ) ;               k = k.next ;               i = i.next ;               j = j.next ;           }           else if(i.pow>j.pow)           {                k.next = new Node( i.coeff , i.pow ) ;                k = k.next ;                i = i.next ;           }           else if(i.pow<j.pow)           {                k.next = new Node( j.coeff , j.pow ) ;                k = k.next ;                j = j.next ;           }                  }              while( i != null)       {               k.next = new Node( i.coeff , i.pow ) ;               k = k.next ;               i = i.next ;       }               while( j  != null)       {               k.next = new Node( j.coeff , j.pow ) ;                k = k.next ;               j = j.next ;       }              return ans.next  ;   }
+1
hanumanmanyam8373 weeks ago
class Solution
{
    public Node reverse(Node head)
    {
        Node curr=head;
        Node prev=null;
        while(curr!=null)
        {
            Node temp=curr.next;
            curr.next=prev;
            prev=curr;
            curr=temp;
        }
        return prev;
    }
    public static Node addPolynomial(Node p1,Node p2)
    {
        //Add your code here.
        Solution s= new Solution();
        Node head1=s.reverse(p1);
        Node head2=s.reverse(p2);
        Node res=new Node(-1,-1);
        Node ans=res;
        int sum=0;
        int pow=0;
        while(head1!=null && head2!=null)
        {
            
            if(head1.pow==head2.pow)
            {
                sum=head1.coeff+head2.coeff;
                pow=head1.pow;
                head1=head1.next;
                head2=head2.next;
                
            }
            else if(head1.pow<head2.pow)
            {
                sum=head1.coeff;
                
                pow=head1.pow;
                head1=head1.next;
                
            }
            else
            {
                sum=head2.coeff;
                pow=head2.pow;
                head2=head2.next;
                
            }
            res.next=new Node(sum,pow);
            res=res.next;
        }
        while(head1!=null)
        {
            sum=head1.coeff;
            pow=head1.pow;
            head1=head1.next;
            res.next=new Node(sum,pow);
            res=res.next;
        }
        while(head2!=null)
        {
            sum=head2.coeff;
            pow=head2.pow;
            head2=head2.next;
            res.next=new Node(sum,pow);
            res=res.next;
        }
        Node com=s.reverse(ans.next);
        return com;
        
    }
}
0
izer0ne4 weeks ago
//------------------O(1) Space Solution--------------

class Solution{
  public:
    Node* addPolynomial(Node *p1, Node *p2)
    {
        // swap p1 with p2 if p2 has element with greater power
        // as we have to make p1 as our resultant list 
        if(p2->pow>p1->pow){
            Node* tmp=p1;
            p1=p2;
            p2=tmp;
        }
        Node* head=p1;
        Node* p1prev=NULL; //keeps track of previous p1 node
        while(p1 && p2){
            // Case 1: if both have element with same power
            if(p1->pow==p2->pow){
                p1->coeff+=p2->coeff; //add p2 to p1
                p1prev=p1; //point prev to curr node
                p1=p1->next;
                Node* tmp=p2; 
                p2=p2->next;
                tmp->next=NULL;
            }
            // Case 2: if p1 has an element with greater power than p2
            else if(p1->pow>p2->pow){
                p1prev=p1;
                p1=p1->next; 
            }
            // Case 3: if p2 has an element eith greater power than p1
            else{
                // add this p2 node to p1 list with the use of p1 prev pointer
                p1prev->next=p2;
                p1prev=p1prev->next;
                p2=p2->next;
            }
        }
        //add the remaining list to our list
        if(p1){
            p1prev->next=p1;
        }
        if(p2){
            p1prev->next=p2;
        }
        return head;
    }
};
 
//try to visualize with the example below
//Hope it helps :)
+1
mashhadihossain1 month ago
SIMPLE JAVA SOLUTION (0.5/1.7 SEC)
class Solution{   public static Node addPolynomial(Node p1,Node p2)   {     //  ArrayList<Node> list=new ArrayList<Node>();      java.util.HashMap<Integer,Integer> map=new java.util.HashMap<Integer,Integer>();       Node temp1=p1;       Node temp2=p2;       while(temp1!=null)       {           map.put(temp1.pow,map.getOrDefault(temp1.pow,0)+temp1.coeff);           temp1=temp1.next;       }        while(temp2!=null)       {           map.put(temp2.pow,map.getOrDefault(temp2.pow,0)+temp2.coeff);           temp2=temp2.next;       }              java.util.ArrayList<Integer> list=new java.util.ArrayList<Integer>(map.keySet());       java.util.Collections.sort(list,java.util.Collections.reverseOrder());       Node dummy=new Node(-1,-1);       Node curr=dummy;       for(int i=0;i<list.size();i++)       {           Node forward=new Node(map.get(list.get(i)),list.get(i));           dummy.next=forward;           dummy=dummy.next;       }       return curr.next;          }}
0
tharabhai2 months ago
C++ iterative Solution:
 
This solution takes O(m+n) Space complexity.
But satisfies Time complexity constraints.
 
Node* addPolynomial(Node *p1, Node *p2)   {       Node* add;              if(p1==NULL)           add = p2;       else if(p2==NULL)           add = p1;       else       {           if(p1->pow==p2->pow)           {               Node* ne = new Node(p1->coeff + p2->coeff, p1->pow);               add = ne;               p1 = p1->next;               p2 = p2->next;           }           else if(p1->pow > p2->pow)           {               Node* ne = new Node(p1->coeff, p1->pow);               add = ne;               p1 = p1->next;           }           else if(p1->pow < p2->pow)           {               Node* ne = new Node(p2->coeff, p2->pow);               add = ne;               p2 = p2->next;           }       }       Node* head = add;       while(p1!=NULL && p2!=NULL)       {           if(p1->pow==p2->pow)           {               Node* ne = new Node(p1->coeff + p2->coeff, p1->pow);               add->next = ne;               add = add->next;               p1 = p1->next;               p2 = p2->next;           }           else if(p1->pow > p2->pow)           {               Node* ne = new Node(p1->coeff, p1->pow);               add->next = ne;               add = add->next;               p1 = p1->next;           }           else if(p1->pow < p2->pow)           {               Node* ne = new Node(p2->coeff, p2->pow);               add->next = ne;               add = add->next;               p2 = p2->next;           }       }       if(p1==NULL)       {           while(p2!=NULL)           {               Node* ne = new Node(p2->coeff, p2->pow);               add->next = ne;               add = add->next;               p2 = p2->next;           }       }       else if(p2==NULL)       {           while(p1!=NULL)           {               Node* ne = new Node(p1->coeff, p1->pow);               add->next = ne;               add = add->next;               p1 = p1->next;           }       }                     return head;   }
0
himanshukug19cs2 months ago
java iterative
 
Node ans=null;      Node node=null;       while(p1!=null||p2!=null){       if(p1!=null&&p2!=null){           if(p1.pow==p2.pow){               if(ans==null){                   ans=new Node(p1.coeff+p2.coeff,p2.pow);                   node=ans;               }               else{                   node.next= new Node(p1.coeff+p2.coeff,p2.pow);                   node=node.next;               }               p1=p1.next;               p2=p2.next;           }           else if(p1.pow>p2.pow){               if(ans==null){                   ans= new Node(p1.coeff,p1.pow);                   node=ans;               }               else{               node.next=new Node(p1.coeff,p1.pow);               node=node.next;               }               p1=p1.next;           }           else{               if(ans==null){                   ans= new Node(p2.coeff,p2.pow);                   node=ans;               }               else{               node.next=new Node(p2.coeff,p2.pow);               node=node.next;               }               p2=p2.next;                      }       }           else if(p1!=null&&p2==null){               if(ans==null){                   ans=new Node(p1.coeff,p1.pow);                   node=ans;               }               else{                   node.next= new Node(p1.coeff,p1.pow);                   node=node.next;               }               p1=p1.next;           }           else if(p1==null&&p2!=null){               if(ans==null){                   ans=new Node(p2.coeff,p2.pow);                   node=ans;               }               else{                   node.next= new Node(p2.coeff,p2.pow);                   node=node.next;               }               p2=p2.next;           }       }             return ans;          }
0
chessnoobdj2 months ago
C++ iterative
Node* addPolynomial(Node *p1, Node *p2)
    {
        struct Node *head = NULL, *tail = NULL; 
        while(p1 && p2){
            while(p1 && p2 && p1->pow>p2->pow){
                append(&head, &tail, p1->coeff, p1->pow);
                p1 = p1->next;
            }
            while(p1 && p2 && p2->pow>p1->pow){
                append(&head, &tail, p2->coeff, p2->pow);
                p2 = p2->next;
            }
            while(p1 && p2 && p1->pow == p2->pow){
                append(&head, &tail, p1->coeff+p2->coeff, p1->pow);
                p1 = p1->next;
                p2 = p2->next;
            }
        }
        while(p1){
            append(&head, &tail, p1->coeff, p1->pow);
            p1 = p1->next;
        }
        while(p2){
            append(&head, &tail, p2->coeff, p2->pow);
            p2 = p2->next;
        }
        return head;
    }
+1
guptanikku5142 months ago
Total Time Taken:
0.0/1.6
Your Accuracy:
100%
class Solution{
  public:
    Node* addPolynomial(Node *p1, Node *p2)
    {
        if(p1==NULL)
        return p2;
        if(p2==NULL)
        return p1;
        if(p1->pow>p2->pow){
        p1->next=addPolynomial(p1->next,p2);
        return p1;
        }
        if(p1->pow<p2->pow){
        p2->next=addPolynomial(p1,p2->next);
        return p2;
        }
        else{
            p1->coeff+=p2->coeff;
            p1->next=addPolynomial(p1->next,p2->next);
            return p1;
        }
    }
};
0
kshubham7672 months ago
class Solution{ public:   /* The below method print the required sum of polynomial   p1 and p2 as specified in output  */   Node* addPolynomial(Node *poly1, Node *poly2)   {       Node *head=NULL,*last=NULL;       //for the first node       if(poly1->pow<poly2->pow)       {           head=last=poly2;           poly2=poly2->next;           last->next=NULL;       }       else if(poly1->pow>poly2->pow)       {           head=last=poly1;           poly1=poly1->next;           last->next=NULL;       }       else       {           poly1->coeff+=poly2->coeff;           head=last=poly1;           poly1=poly1->next;           poly2=poly2->next;           last->next=NULL;       }       //remaining node       while(poly1&&poly2)       {           if(poly1->pow<poly2->pow)       {           last->next=poly2;           last=poly2;           poly2=poly2->next;       }       else if(poly1->pow>poly2->pow)       {           last->next=poly1;           last=poly1;           poly1=poly1->next;       }       else       {           poly1->coeff+=poly2->coeff;           last->next=poly1;           last=poly1;           poly1=poly1->next;           poly2=poly2->next;       }       }       //if one of polynomial ended then remaining from other will be linked       if(poly1)last->next=poly1;       if(poly2)last->next=poly2;       return head;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.