Problem 232439 · medium · Phase 02 Linear Data Structures

Circular Window Sums

arrays · sliding window · modular indexing

Given a list of integers nums and a positive integer k no larger than its length, return a list out of the same length where out[i] is the sum of the k consecutive elements starting at index i, wrapping around to the beginning of the list when the window runs past the end.

Examples

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

Input:  nums = [2, 2, 2, 2, 2], k = 4
Output: [8, 8, 8, 8, 8]

Constraints

  • 0 <= len(nums) <= 10**5
  • 1 <= k <= len(nums) (for an empty list return [])
  • Return a new list.
  • Target: O(n) time; summing k elements per position is too slow.

Goals

  • Index a list cyclically with the modulo operator
  • Slide a window that wraps past the end
  • Produce exactly one sum per starting position
Starting Python…