LeetCode(Problem Of Day)

LeetCode(Problem Of Day)

Initials thinking for the problem :-

1.Just noobs thinking(common person) by seeing the statement , reverse the list L1 and L2 , then calculate the sum , then reverse that calculated sum which finally give our answer , as common addition of two number.

2. As we see if we follow the step -1 approach we required to reverse the first two given Linked list L1 and L2 which going to take O(L1)+O(L2) + O( output result length) and much more.

3. As a programmer we drop this initial though on looking to Time Optimization , then we see the i/o we get idea we iterate the list L1 and L2 , and adds up , if carry is generated then , we move the carry in creation of next node and adds the value up their.

Now the Algorithm we Apply for this:-

  1. Declare the Dummy node , to return the head of resultant list , temp for the iteration to Linking the nodes.
  2. We perform the iteration , until list 1 !=null or list 2!=null or else carry!=0.
  3. Iterate the L1 and L2 list and if the node value found not to be null , then we we add it value to in the total .
  4. If carry is generated then we have to add the carry count , on the next linking node value.
  5. After that we find the remainder of total value and make the new node of it , and also find carry from it.
  6. After that we return the head of resultant Linked List.

Time and Space Complexity:-

Time:- O(max(L1,L2)):-> Time is the max length of both of L1 and L2 , as we have to iterate over the both list fully.

Space :- O(N) :->To creating the new Linked List contains the summation of both L1 and L2.

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

Code:-

No alt text provided for this image


要查看或添加评论,请登录

社区洞察

其他会员也浏览了