Time limit exceeded adding two numbers represented by linked lists of digits

Viewed 30

Question Link - https://leetcode.com/problems/add-two-numbers/

Let the number of nodes in L1 be m and the number of nodes in L2 be n. The time complexity of my solution should be O(max(m,n)).

So, can anyone please explain to me why I am getting a TLE in this test case?

l1 = [2, 4, 9]
l2 = [5, 6, 4, 9]

/* Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int x = 0 , y = 0;
        ListNode *result = new ListNode();
        ListNode *ptr = result;
        int carry = 0, sum = 0;
        
        while(l1 != NULL || l2 != NULL)
        {
           if(l1 != NULL && l2 != NULL)
           {
               int x = l1->val;
               l1 = l1->next;
               
               int y = l2->val;
               l2 = l2->next;
               
                sum = x + y + carry;
               carry = sum / 10;
               
               // cout<next = temp;
               ptr = ptr->next; 
           }
            
            else if(l1 != NULL && l2 == NULL)
            {
                int x = l1->val;
                l1 = l1->next;
                
                sum = x + carry;
                carry = sum / 10;
                
                ListNode *temp = new ListNode(sum%10);
                ptr->next = temp;
                ptr = ptr->next;
            }
            
            else
            {
                 int x = l2->val;
                l1 = l2->next;
                
                sum = x + carry;
                carry = sum / 10;
                
                ListNode *temp = new ListNode(sum%10);
                ptr->next = temp;
                ptr = ptr->next;
            }
           
        }
         if(carry != 0)
            {
                ListNode *temp = new ListNode(carry);
                ptr->next = temp;
                ptr = ptr->next;
            }
            
      
        
        return result->next;
    }
};
1 Answers

Inside the while loop, when l1 is NULL and l2 is not NULL, l1 = l2->next; should be l2 = l2->next;

Related