Return the sum of every contiguous subarray of length k

Quick Overview

Given an integer array and a window length k, return the sum of every contiguous subarray of length k, ordered by starting index. The problem tests the fixed-size sliding window pattern, constant-time running-sum updates, and getting the window count and indices right.

Return the sum of every contiguous subarray of length k

Company: EPAM Systems

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given an array of integers `nums` and an integer `k`, return an array of sums of every **contiguous subarray** of size `k`. You must use a sliding window approach to calculate the sums efficiently. The result should contain `n - k + 1` elements, where `n` is the length of `nums`. The i-th element of the result (0-based) is the sum of `nums[i..i+k-1]`. ### Function Signature ```python def subarray_sums(nums: list[int], k: int) -> list[int]: ``` ### Constraints - `1 <= nums.length <= 10^5` - `-10^4 <= nums[i] <= 10^4` - `1 <= k <= nums.length` ### Examples ```text Input: nums = [1,2,3,4,5], k = 3 Output: [6,9,12] ``` The subarrays of size 3 are [1,2,3], [2,3,4] and [3,4,5], with sums 6, 9 and 12. ```text Input: nums = [2,-1,5,3,-2,4], k = 2 Output: [1,4,8,1,2] ``` The subarrays of size 2 are [2,-1], [-1,5], [5,3], [3,-2] and [-2,4], with sums 1, 4, 8, 1 and 2. ```text Input: nums = [7,-3,2], k = 3 Output: [6] ``` When `k` equals the array length there is exactly `n - k + 1 = 1` window, the whole array, and its sum is 7 + (-3) + 2 = 6.

Overview: Given an integer array and a window length k, return the sum of every contiguous subarray of length k, ordered by starting index. The problem tests the fixed-size sliding window pattern, constant-time running-sum updates, and getting the window count and indices right.

EPAM Systems logo
EPAM Systems
Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given an array of integers nums and an integer k, return an array of sums of every contiguous subarray of size k.

You must use a sliding window approach to calculate the sums efficiently. The result should contain n - k + 1 elements, where n is the length of nums. The i-th element of the result (0-based) is the sum of nums[i..i+k-1].

Function Signature

def subarray_sums(nums: list[int], k: int) -> list[int]:

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

Examples

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

The subarrays of size 3 are [1,2,3], [2,3,4] and [3,4,5], with sums 6, 9 and 12.

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

The subarrays of size 2 are [2,-1], [-1,5], [5,3], [3,-2] and [-2,4], with sums 1, 4, 8, 1 and 2.

Input: nums = [7,-3,2], k = 3
Output: [6]

When k equals the array length there is exactly n - k + 1 = 1 window, the whole array, and its sum is 7 + (-3) + 2 = 6.