Can i use this solution in interviews?


#1

ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {

    int carry=0;

    vector<int>v;

    ListNode* temp=A;

    ListNode* temp1=B;

    while((temp!=NULL)&&(temp1!=NULL))

    {

        int d=temp->val+temp1->val+carry;

        if(d>=10)

        {

            carry=1;

            d=d%10;

        }

        else carry=0;

       v.push_back(d);

       temp=temp->next;

       temp1=temp1->next;

    }

    while(temp!=NULL)

    {

        int d=temp->val+carry;

        if(d>=10)

        {

            carry=1;

            d=d%10;

        }

        else carry=0;

       v.push_back(d);

       temp=temp->next;

    }

    while(temp1!=NULL)

    {

         int d=temp1->val+carry;

        if(d>=10)

        {

            carry=1;

            d=d%10;

        }

        else carry=0;

       v.push_back(d);

       temp1=temp1->next;

    }

    if(carry==1)

    {

        v.push_back(1);

    }

    ListNode* temp2=new ListNode(v[0]);

    ListNode* C=temp2;

    for(int i=1;i<v.size();i++)

    {

        ListNode* temp3=new ListNode(v[i]);

        temp2->next=temp3;

        temp2=temp2->next;

    }

    return C;

}


#2

You are using extra space in the form of vector. So mostly the interviewer will ask you to reduce the space complexity. Try to do addition in place.