[Naive Approach] Two Traversals - O(n) Time O(1) Space
The idea is to first find the total number of nodes in the linked list. Once the length is known, we skip the first (len - n) nodes and then traverse the remaining last n nodes, accumulating their sum.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// your task is to complete this function// function should return sum of last n nodesintsumofNodes(Node*head,intn){// if n == 0if(n<=0)return0;intsum=0,len=0;Node*temp=head;// calculate the length of the linked listwhile(temp!=nullptr){len++;temp=temp->next;}// count of first (len - n) nodesintc=len-n;temp=head;// just traverse the 1st 'c' nodeswhile(temp!=nullptr&&c--)temp=temp->next;// now traverse the last 'n' nodes and add themwhile(temp!=nullptr){// accumulate node's data to sumsum+=temp->data;// move to next nodetemp=temp->next;}// required sumreturnsum;}//Driver Codeintmain(){// create linked list 5->9->6->3->4->10Node*head=newNode(5);head->next=newNode(9);head->next->next=newNode(6);head->next->next->next=newNode(3);head->next->next->next->next=newNode(4);head->next->next->next->next->next=newNode(10);intn=3;cout<<sumofNodes(head,n);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*newNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->next=NULL;returnnode;}// your task is to complete this function// function should return sum of last n nodesintsumofNodes(structNode*head,intn){// if n == 0if(n<=0)return0;intsum=0,len=0;structNode*temp=head;// calculate the length of the linked listwhile(temp!=NULL){len++;temp=temp->next;}// count of first (len - n) nodesintc=len-n;temp=head;// just traverse the 1st 'c' nodeswhile(temp!=NULL&&c--)temp=temp->next;// now traverse the last 'n' nodes and add themwhile(temp!=NULL){// accumulate node's data to sumsum+=temp->data;// move to next nodetemp=temp->next;}// required sumreturnsum;}// Driver Codeintmain(){// create linked list 5->9->6->3->4->10structNode*head=newNode(5);head->next=newNode(9);head->next->next=newNode(6);head->next->next->next=newNode(3);head->next->next->next->next=newNode(4);head->next->next->next->next->next=newNode(10);intn=3;printf("%d",sumofNodes(head,n));return0;}
Java
classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// your task is to complete this function// function should return sum of last n nodespublicstaticintsumofNodes(Nodehead,intn){// if n == 0if(n<=0)return0;intsum=0,len=0;Nodetemp=head;// calculate the length of the linked listwhile(temp!=null){len++;temp=temp.next;}// count of first (len - n) nodesintc=len-n;temp=head;// just traverse the 1st 'c' nodeswhile(temp!=null&&c-->0)temp=temp.next;// now traverse the last 'n' nodes and add themwhile(temp!=null){// accumulate node's data to sumsum+=temp.data;// move to next nodetemp=temp.next;}// required sumreturnsum;}publicstaticvoidmain(String[]args){// create linked list 5->9->6->3->4->10Nodehead=newNode(5);head.next=newNode(9);head.next.next=newNode(6);head.next.next.next=newNode(3);head.next.next.next.next=newNode(4);head.next.next.next.next.next=newNode(10);intn=3;System.out.print(sumofNodes(head,n));}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# your task is to complete this function# function should return sum of last n nodesdefsumofNodes(head,n):# if n == 0ifn<=0:return0sum=0length=0temp=head# calculate the length of the linked listwhiletempisnotNone:length+=1temp=temp.next# count of first (len - n) nodesc=length-ntemp=head# just traverse the 1st 'c' nodeswhiletempisnotNoneandc>0:temp=temp.nextc-=1# now traverse the last 'n' nodes and add themwhiletempisnotNone:# accumulate node's data to sumsum+=temp.data# move to next nodetemp=temp.next# required sumreturnsumif__name__=="__main__":# create linked list 5->9->6->3->4->10head=Node(5)head.next=Node(9)head.next.next=Node(6)head.next.next.next=Node(3)head.next.next.next.next=Node(4)head.next.next.next.next.next=Node(10)n=3print(sumofNodes(head,n))
C#
usingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGfG{// your task is to complete this function// function should return sum of last n nodespublicintsumofNodes(Nodehead,intn){// if n == 0if(n<=0)return0;intsum=0,len=0;Nodetemp=head;// calculate the length of the linked listwhile(temp!=null){len++;temp=temp.next;}// count of first (len - n) nodesintc=len-n;temp=head;// just traverse the 1st 'c' nodeswhile(temp!=null&&c-->0)temp=temp.next;// now traverse the last 'n' nodes and add themwhile(temp!=null){// accumulate node's data to sumsum+=temp.data;// move to next nodetemp=temp.next;}// required sumreturnsum;}//Driver CodepublicstaticvoidMain(){// create linked list 5->9->6->3->4->10Nodehead=newNode(5);head.next=newNode(9);head.next.next=newNode(6);head.next.next.next=newNode(3);head.next.next.next.next=newNode(4);head.next.next.next.next.next=newNode(10);intn=3;GfGobj=newGfG();Console.WriteLine(obj.sumofNodes(head,n));}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;}}// your task is to complete this function// function should return sum of last n nodesfunctionsumofNodes(head,n){// if n == 0if(n<=0)return0;letsum=0,len=0;lettemp=head;// calculate the length of the linked listwhile(temp!==null){len++;temp=temp.next;}// count of first (len - n) nodesletc=len-n;temp=head;// just traverse the 1st 'c' nodeswhile(temp!==null&&c--)temp=temp.next;// now traverse the last 'n' nodes and add themwhile(temp!==null){// accumulate node's data to sumsum+=temp.data;// move to next nodetemp=temp.next;}// required sumreturnsum;}// driver code// create linked list 5->9->6->3->4->10lethead=newNode(5);head.next=newNode(9);head.next.next=newNode(6);head.next.next.next=newNode(3);head.next.next.next.next=newNode(4);head.next.next.next.next.next=newNode(10);letn=3;console.log(sumofNodes(head,n));
Output
17
Time Complexity: O(n),where n is the number of nodes in the linked list. Auxiliary Space: O(1)
[Expected Approach] Single Traversal - O(n) Time O(1) Space
The idea is to use a two-pointer (sliding window) technique to find the sum of the last n nodes in a single traversal. We maintain a window of size n. First, we compute the sum of the first n nodes. Then, we slide the window forward by adding the next node and removing the previous node’s contribution.
Let us understand with an example:
Linked List: 5 -> 9 -> 6 -> 3 -> 4 -> 10, n = 3
Start traversal: Initialize sum = 0, temp = 0 First 3 nodes:
At 5 -> sum = 5
At 9 -> sum = 14
At 6 -> sum = 20
Now slide window:
At 3 -> sum = 23, temp = 5
At 4 -> sum = 27, temp = 14
At 10 -> sum = 37, temp = 20
All nodes processed. Final value = sum - temp = 17
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to calculate the sum of the last n nodes in a linked listintsumofNodes(Node*head,intn){// If n is less than or equal to 0, return 0if(n<=0)return0;intsum=0,temp=0;Node*ref_ptr,*main_ptr;ref_ptr=main_ptr=head;// Calculate the sum of the first n nodeswhile(ref_ptr!=nullptr&&n--){sum+=ref_ptr->data;ref_ptr=ref_ptr->next;}// Calculate the sum of the remaining nodeswhile(ref_ptr!=nullptr){temp+=main_ptr->data;sum+=ref_ptr->data;main_ptr=main_ptr->next;ref_ptr=ref_ptr->next;}// Return the sum of the last n nodesreturn(sum-temp);}// Driver Codeintmain(){Node*head=newNode(5);head->next=newNode(9);head->next->next=newNode(6);head->next->next->next=newNode(3);head->next->next->next->next=newNode(4);head->next->next->next->next->next=newNode(10);intn=3;cout<<sumofNodes(head,n);return0;}
C
#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to create a new nodestructNode*newNode(intx){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=x;node->next=NULL;returnnode;}// Function to calculate the sum of the last n nodes in a linked listintsumofNodes(structNode*head,intn){// If n is less than or equal to 0, return 0if(n<=0)return0;intsum=0,temp=0;structNode*ref_ptr,*main_ptr;ref_ptr=main_ptr=head;// Calculate the sum of the first n nodeswhile(ref_ptr!=NULL&&n--){sum+=ref_ptr->data;ref_ptr=ref_ptr->next;}// Calculate the sum of the remaining nodeswhile(ref_ptr!=NULL){temp+=main_ptr->data;sum+=ref_ptr->data;main_ptr=main_ptr->next;ref_ptr=ref_ptr->next;}// Return the sum of the last n nodesreturn(sum-temp);}// Driver Codeintmain(){structNode*head=newNode(5);head->next=newNode(9);head->next->next=newNode(6);head->next->next->next=newNode(3);head->next->next->next->next=newNode(4);head->next->next->next->next->next=newNode(10);intn=3;printf("%d",sumofNodes(head,n));return0;}
Java
importjava.util.*;classNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to calculate the sum of the last n nodes in// a linked listpublicstaticintsumofNodes(Nodehead,intn){// If n is less than or equal to 0, return 0if(n<=0)return0;intsum=0,temp=0;Noderef_ptr,main_ptr;ref_ptr=main_ptr=head;// Calculate the sum of the first n nodeswhile(ref_ptr!=null&&n-->0){sum+=ref_ptr.data;ref_ptr=ref_ptr.next;}// Calculate the sum of the remaining nodeswhile(ref_ptr!=null){temp+=main_ptr.data;sum+=ref_ptr.data;main_ptr=main_ptr.next;ref_ptr=ref_ptr.next;}// Return the sum of the last n nodesreturn(sum-temp);}publicstaticvoidmain(String[]args){Nodehead=newNode(5);head.next=newNode(9);head.next.next=newNode(6);head.next.next.next=newNode(3);head.next.next.next.next=newNode(4);head.next.next.next.next.next=newNode(10);intn=3;System.out.print(sumofNodes(head,n));}}
Python
classNode:def__init__(self,x):self.data=xself.next=None# Function to calculate the sum of the last n nodes in a linked listdefsumofNodes(head,n):# If n is less than or equal to 0, return 0ifn<=0:return0sum=0temp=0ref_ptr=headmain_ptr=head# Calculate the sum of the first n nodeswhileref_ptrisnotNoneandn:sum+=ref_ptr.dataref_ptr=ref_ptr.nextn-=1# Calculate the sum of the remaining nodeswhileref_ptrisnotNone:temp+=main_ptr.datasum+=ref_ptr.datamain_ptr=main_ptr.nextref_ptr=ref_ptr.next# Return the sum of the last n nodesreturn(sum-temp)# Driver Codeif__name__=="__main__":head=Node(5)head.next=Node(9)head.next.next=Node(6)head.next.next.next=Node(3)head.next.next.next.next=Node(4)head.next.next.next.next.next=Node(10)n=3print(sumofNodes(head,n))
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to calculate the sum of the last n nodes in a linked listpublicintsumofNodes(Nodehead,intn){// If n is less than or equal to 0, return 0if(n<=0)return0;intsum=0,temp=0;Noderef_ptr,main_ptr;ref_ptr=main_ptr=head;// Calculate the sum of the first n nodeswhile(ref_ptr!=null&&n-->0){sum+=ref_ptr.data;ref_ptr=ref_ptr.next;}// Calculate the sum of the remaining nodeswhile(ref_ptr!=null){temp+=main_ptr.data;sum+=ref_ptr.data;main_ptr=main_ptr.next;ref_ptr=ref_ptr.next;}// Return the sum of the last n nodesreturn(sum-temp);}publicstaticvoidMain(){Nodehead=newNode(5);head.next=newNode(9);head.next.next=newNode(6);head.next.next.next=newNode(3);head.next.next.next.next=newNode(4);head.next.next.next.next.next=newNode(10);intn=3;GfGobj=newGfG();Console.Write(obj.sumofNodes(head,n));}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to calculate the sum of the last n nodes in a linked listfunctionsumofNodes(head,n){// If n is less than or equal to 0, return 0if(n<=0)return0;letsum=0,temp=0;letref_ptr=head,main_ptr=head;// Calculate the sum of the first n nodeswhile(ref_ptr!=null&&n-->0){sum+=ref_ptr.data;ref_ptr=ref_ptr.next;}// Calculate the sum of the remaining nodeswhile(ref_ptr!=null){temp+=main_ptr.data;sum+=ref_ptr.data;main_ptr=main_ptr.next;ref_ptr=ref_ptr.next;}// Return the sum of the last n nodesreturn(sum-temp);}// Driver Codelethead=newNode(5);head.next=newNode(9);head.next.next=newNode(6);head.next.next.next=newNode(3);head.next.next.next.next=newNode(4);head.next.next.next.next.next=newNode(10);letn=3;console.log(sumofNodes(head,n));
Output
17
Time Complexity: O(n), where n is the number of nodes in the linked list. Auxiliary Space: O(1)