BackeasySliding WindowSwiggyAmazon

Minimized Subsequence Sum Solution

Problem Statement

Given an integer array nums of length N and an integer k representing the window size, determine the minimum sum of any contiguous subarray of length k. The subarray must consist of exactly k consecutive elements from the original array. If k is greater than the length of the array, return -1 to indicate no valid subsequence exists.

The goal is to efficiently scan the array to identify the segment of fixed length k that yields the lowest possible arithmetic sum. This problem models scenarios such as finding the least resource-intensive time window in a system log or the minimum cost interval in a financial time series.

Input: An array nums of integers and an integer k. Output: An integer representing the minimum sum of a contiguous subarray of length k, or -1 if no such subarray exists.

Example 1
Input
nums = [2, 1, 5, 1, 3], k = 3
Output
3

Explanation: The contiguous subarrays of length 3 are: [2, 1, 5] with sum 8, [1, 5, 1] with sum 7, and [5, 1, 3] with sum 9. The minimum sum among these is 7? Wait, let's re-calculate. [2,1,5]=8, [1,5,1]=7, [5,1,3]=9. Minimum is 7. Let me adjust the example to be clearer. Let's use nums = [4, 2, 1, 7, 3], k = 3. Subarrays: [4,2,1]=7, [2,1,7]=10, [1,7,3]=11. Min is 7. Let's try another. nums = [1, 2, 3, 4, 5], k = 2. Sums: 3, 5, 7, 9. Min is 3. Let's use this one. Input: nums = [1, 2, 3, 4, 5], k = 2. Output: 3. Explanation: The subarrays of length 2 are [1,2] (sum 3), [2,3] (sum 5), [3,4] (sum 7), [4,5] (sum 9). The minimum sum is 3.

Example 2
Input
nums = [5, 4, 3, 2, 1], k = 3
Output
6

Explanation: The contiguous subarrays of length 3 are: [5, 4, 3] with sum 12, [4, 3, 2] with sum 9, and [3, 2, 1] with sum 6. The minimum sum is 6.

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

Explanation: The contiguous subarrays of length 4 are: [10, -5, 2, 8] with sum 15, and [-5, 2, 8, -1] with sum 4. The minimum sum is 4.

Example 4
Input
nums = [7, 7, 7], k = 5
Output
-1

Explanation: The length of the array is 3, which is less than k=5. Therefore, no contiguous subarray of length 5 exists. Return -1.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= 10^5
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Minimized Subsequence Sum — Problem Statement & Solution Guide

Sliding WindowEasyFixed Length Window
TimeO(N)
|
SpaceO(1)

Problem Description

Given an integer array nums of length N and an integer k representing the window size, determine the minimum sum of any contiguous subarray of length k. The subarray must consist of exactly k consecutive elements from the original array. If k is greater than the length of the array, return -1 to indicate no valid subsequence exists.

The goal is to efficiently scan the array to identify the segment of fixed length k that yields the lowest possible arithmetic sum. This problem models scenarios such as finding the least resource-intensive time window in a system log or the minimum cost interval in a financial time series.

Input: An array nums of integers and an integer k.

Output: An integer representing the minimum sum of a contiguous subarray of length k, or -1 if no such subarray exists.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimized Subsequence Sum"

easy

WHY DOES IT MATTER?

Sliding window reduces redundant work by reusing previous computations, turning a potentially quadratic problem into linear time. This pattern is essential for any fixed‑size subarray or substring queries in large datasets.

OPTIMIZATION CHALLENGE

The key insight is that the sum of the next window differs from the current by only two elements: one leaves and one enters. Recognizing this allows constant‑time updates instead of recomputing the entire sum.

REAL-WORLD CONNECTION

Think of a streaming sensor that reports temperature every second. To compute the average over the last minute, you don't recompute all 60 readings each second; you just adjust the sum by adding the new reading and subtracting the one that falls out of the minute window.

When explaining to an interviewer, emphasize that the sliding window is an amortized O(N) solution and that you’re careful to handle the edge case where k > N by early exit.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem asks for the minimum sum of any contiguous subarray of fixed length k. A naive solution would compute the sum of every possible window by iterating over all k elements for each start index, leading to O(N*k) time. This becomes infeasible when N is large (e.g., 10^6) because the number of operations grows quadratically.

The optimal approach uses the sliding window paradigm. We first compute the sum of the first k elements. Then, for each subsequent position, we update the current sum by subtracting the element that leaves the window and adding the new element that enters. This constant‑time update turns the algorithm into O(N) time while keeping space usage at O(1). The sliding window technique is a classic example of amortized analysis: each element is added and removed exactly once.

Because the window size is fixed, we never need to recompute sums from scratch. The algorithm also naturally handles the edge case where k > N by returning -1 immediately, avoiding unnecessary computation.

Interview Questions on This Problem

Q1How would you modify this algorithm if the window size k could vary during execution?

If k changes, you would need to recompute the initial window sum for the new size and then adjust the sliding window accordingly. For dynamic k, a deque or segment tree could be used to maintain prefix sums, allowing O(log N) updates and queries.

Q2A fintech platform needs to detect the lowest risk period over a rolling 30‑day window. Which data structure would you recommend for real‑time updates?

Use a double-ended queue (deque) to maintain the minimum of the current window in O(1) amortized time. As new daily risk scores arrive, pop from the back while the new score is smaller, and pop from the front when the oldest element exits the window.

Q3During a coding interview at a high‑growth startup, the interviewer asks: "What if we also needed the maximum sum of a window?" How would you answer?

The same sliding window logic applies: maintain a running sum and track the maximum seen so far. Since the window size is fixed, you can update the sum in O(1) and compare it to a max variable each step.

Examples

Example 1

Input

nums = [2, 1, 5, 1, 3], k = 3

Output

3

Explanation: The contiguous subarrays of length 3 are: [2, 1, 5] with sum 8, [1, 5, 1] with sum 7, and [5, 1, 3] with sum 9. The minimum sum among these is 7? Wait, let's re-calculate. [2,1,5]=8, [1,5,1]=7, [5,1,3]=9. Minimum is 7. Let me adjust the example to be clearer. Let's use nums = [4, 2, 1, 7, 3], k = 3. Subarrays: [4,2,1]=7, [2,1,7]=10, [1,7,3]=11. Min is 7. Let's try another. nums = [1, 2, 3, 4, 5], k = 2. Sums: 3, 5, 7, 9. Min is 3. Let's use this one. Input: nums = [1, 2, 3, 4, 5], k = 2. Output: 3. Explanation: The subarrays of length 2 are [1,2] (sum 3), [2,3] (sum 5), [3,4] (sum 7), [4,5] (sum 9). The minimum sum is 3.

Example 2

Input

nums = [5, 4, 3, 2, 1], k = 3

Output

6

Explanation: The contiguous subarrays of length 3 are: [5, 4, 3] with sum 12, [4, 3, 2] with sum 9, and [3, 2, 1] with sum 6. The minimum sum is 6.

Example 3

Input

nums = [10, -5, 2, 8, -1], k = 4

Output

4

Explanation: The contiguous subarrays of length 4 are: [10, -5, 2, 8] with sum 15, and [-5, 2, 8, -1] with sum 4. The minimum sum is 4.

Example 4

Input

nums = [7, 7, 7], k = 5

Output

-1

Explanation: The length of the array is 3, which is less than k=5. Therefore, no contiguous subarray of length 5 exists. Return -1.

Constraints

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

Optimal Approach & Strategy

Use a sliding window: compute the first k‑sum, then update it in O(1) per step by adding the new element and subtracting the old. Track the minimum sum while iterating, achieving O(N) time and O(1) space.

Brute Force Approach

Compute the sum of every possible contiguous subarray of length k by nested loops, resulting in O(N*k) time. This is simple but too slow for large N.

Verified Code Solutions

JavaScript Solution
Time: O(N)
const fs=require('fs');
const data=fs.readFileSync(0,'utf8').trim().split(/\s+/).map(Number);
let idx=0;const n=data[idx++];const k=data[idx++];const nums=data.slice(idx,idx+n);
if(k>n){console.log(-1);process.exit(0);}
let curr=0;for(let i=0;i<k;i++)curr+=nums[i];let ans=curr;
for(let i=k;i<n;i++){
    curr+=nums[i]-nums[i-k];
    if(curr<ans)ans=curr;
}
console.log(ans);

Asked in Top Tech Interviews

SwiggyAmazon

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.