700594. Find the Sum of Last N nodes of the Linked List
Easy
Find the Sum of Last N nodes of the Linked List
Slug: find-the-sum-of-last-n-nodes-of-the-linked-list
Difficulty: Easy
Id: 700594
Topic Tags: Linked List, Data Structures
Company Tags: None
Summary
Given a linked list and an integer n, find the sum of the last n nodes in the linked list. This problem is related to data structures and manipulation of linked lists.
Detailed Explanation
To solve this problem, we will traverse the linked list from the end to the beginning. We keep track of the sum of the last n nodes as we iterate through the linked list.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
sumto 0. - Traverse the linked list from the end to the beginning using a pointer
p. - As you traverse, keep track of the sum of the last
nnodes by adding each node's value tosum. - Return
sum.
The time complexity for this solution is O(L), where L is the length of the linked list, since we need to traverse the entire list. The space complexity is O(1) as we only use a constant amount of space to store the sum.
Here's an ASCII art diagram illustrating the traversal:
5 -> 4 -> 3 -> 2 -> 1
^
p (starts at the end)
Optimized Solutions
Java
class Solution {
public int findSum(int n, Node head) {
int sum = 0;
Node p = head;
for (int i = 0; i < n; i++) {
sum += p.data;
p = p.next;
}
return sum;
}
}