1574. Tail Window Total

Easy1.5 points estimatedLinked ListTwo Pointers

A shop logs its daily takings in a singly linked list, oldest day first, and the owner wants the total of the most recent k days. Given head and an integer k, return the sum of the values of the last k nodes as a 64-bit integer. The value of k is always between 1 and the length of the list, and node values may be negative and as large as 10^9 in absolute value, so the sum can exceed the 32-bit range. Use a lead pointer that starts k nodes ahead and a trail pointer that starts at the head, move both until the lead falls off, then add up the nodes from the trail onward. The list has 1 to 1000 nodes. Aim for O(n) time and O(1) extra space.

Example 1

Input:
head = [1,2,3,4,5], k = 2
Output:
9
Explanation:

The last two values are 4 and 5, which add up to 9.

Example 2

Input:
head = [-1,-2,-3], k = 3
Output:
-6
Explanation:

The window is the whole list and the total is -6.

Constraints

1 ≤ k ≤ length ≤ 1000

-109 ≤ val ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…