Find the Sum of Last N nodes of the Linked List | Linked List | GFG POTD | C++ | Java | Code Kar Lo

preview_player
Показать описание
Given a single linked list, calculate the sum of the last n nodes.

0:00 Introduction
0:11 Problem Statement
0:43 Explanation
2:51 C++ Code
4:34 AI Review
5:58 Java Code

gfg potd
gfg potd today
gfg problem of the day
potd gfg
potd
potd today
gfg

#dsa #datastructures #algorithm #gfg #potd #coding #array #strings #tree #binarysearchtree #codekarlo #dynamicprogramming
Рекомендации по теме
Комментарии
Автор

Solved by own with the same approach bas ye difference tha ki, me 1st while loop me hi pure linked list ka sum le iya and then again count-=n kiya or 2nd while loop me while(count) -> sum-=temp->data. kar diya. Thank you bhaiyya.

salmaniproductions
Автор

We can do this in single traversal using a queue of fixed size (n -> number of end nodes), for each node we add the node->value to sum variable and push the node->value to queue and if queue length exceeds 'n', we pop from front and subtract the popped value from sum.
But this approach increases our space complexity to O(n), n =number of nodes at end.

We can also use a map to store sum but the space complexity of using a map will be O(L), L = length of given list

Shotnshorts
Автор

public int sumOfLastN_nodes(Node head, int n){
Node prev=0, cur=0;
int cnt=0;
while(prev!=null){
if(cnt>=n){
cur=cur.next;
}
prev=prev.next;
cnt++;
}
int sum=0;
while(cur!=null){
sum+=cur.data;
cur=cur.next;
}
return sum;
}
🎉❤

dayashankarlakhotia