Problem 210303 · easy · Phase 02 Linear Data Structures

Sums of Every Window

arrays · sliding window · running sum

Given a list of integers nums and a positive integer k, return a list containing the sum of every contiguous window of exactly k elements, from left to right. If k is larger than the list, return [].

Examples

Input:  nums = [1, 2, 3, 4, 5], k = 3
Output: [6, 9, 12]
Explanation: 1+2+3, 2+3+4, 3+4+5.

Input:  nums = [1, 2, 3], k = 4
Output: []

Constraints

  • 0 <= len(nums) <= 10**5
  • 1 <= k <= 10**5
  • Return a new list.
  • Target: O(n) time; summing each window from scratch is too slow when k is large.

Goals

  • Maintain a running window sum instead of re-summing each slice
  • Return one value per window position
  • Handle k larger than the list
Starting Python…