BackeasySliding WindowZomatoTCS

Minimized Path Weight Solution

Problem Statement

Consider a linear sequence of nodes where each node carries a specific weight value. You are tasked with identifying a contiguous segment of exactly K nodes that yields the lowest cumulative weight. This scenario models a path optimization problem where the cost is strictly additive and the segment length is fixed.

Given an integer array weights of size N and an integer K, compute the minimum sum of any subarray of length K. The solution must efficiently scan the array to find the optimal window without recalculating the sum from scratch for every position.

Input Format: The first line contains two space-separated integers, N and K, representing the total number of nodes and the required segment length, respectively. The second line contains N space-separated integers representing the weights of the nodes in order.

Output Format: Print a single integer representing the minimum possible sum of a contiguous subarray of length K.

Example 1
Input
5 3 4 2 1 7 3
Output
7

Explanation: The array is [4, 2, 1, 7, 3] and K=3. The possible windows are: [4, 2, 1] with sum 7; [2, 1, 7] with sum 10; [1, 7, 3] with sum 11. The minimum sum is 7.

Example 2
Input
4 2 -1 5 -2 3
Output
-3

Explanation: The array is [-1, 5, -2, 3] and K=2. The windows are: [-1, 5] with sum 4; [5, -2] with sum 3; [-2, 3] with sum 1. Wait, let's re-calculate. [-1, 5] = 4. [5, -2] = 3. [-2, 3] = 1. The minimum is 1. Let me pick a better example for negative numbers. Let's use [10, -5, 2, 8] with K=2. Windows: [10, -5]=5, [-5, 2]=-3, [2, 8]=10. Min is -3. Let's use that.

Example 3
Input
4 2 10 -5 2 8
Output
-3

Explanation: The array is [10, -5, 2, 8] and K=2. The windows are: [10, -5] with sum 5; [-5, 2] with sum -3; [2, 8] with sum 10. The minimum sum is -3.

Example 4
Input
1 1 42
Output
42

Explanation: The array is [42] and K=1. There is only one window: [42] with sum 42. The minimum sum is 42.

Constraints

  • 1 <= N <= 10^5
  • 1 <= K <= N
  • -10^9 <= weights[i] <= 10^9
  • The sum of any subarray fits within a 64-bit integer.
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 Path Weight — Problem Statement & Solution Guide

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

Problem Description

Consider a linear sequence of nodes where each node carries a specific weight value. You are tasked with identifying a contiguous segment of exactly K nodes that yields the lowest cumulative weight. This scenario models a path optimization problem where the cost is strictly additive and the segment length is fixed.

Given an integer array weights of size N and an integer K, compute the minimum sum of any subarray of length K. The solution must efficiently scan the array to find the optimal window without recalculating the sum from scratch for every position.

Input Format:

The first line contains two space-separated integers, N and K, representing the total number of nodes and the required segment length, respectively. The second line contains N space-separated integers representing the weights of the nodes in order.

Output Format:

Print a single integer representing the minimum possible sum of a contiguous subarray of length K.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Minimized Path Weight"

easy

WHY DOES IT MATTER?

Sliding‑window patterns are fundamental for any problem that asks for aggregate information over a fixed‑size contiguous range. Recognizing this pattern lets you replace nested loops with a single pass, dramatically reducing runtime and making the solution scalable.

OPTIMIZATION CHALLENGE

The key insight is that adjacent windows share K‑1 elements. By reusing the previous window's sum and adjusting for the one element that exits and the one that enters, you eliminate the O(K) recomputation for each shift, collapsing the overall complexity to O(N).

REAL-WORLD CONNECTION

Think of a network router that monitors traffic over the last 5 seconds to detect spikes. Instead of recomputing the total bytes every millisecond, it updates the total by removing the oldest second's count and adding the newest, exactly like a sliding window over a time series.

During an interview, compute the first window sum explicitly, then write a tight loop that updates the sum in place. Keep a separate variable for the best (minimum) sum seen so far; this avoids extra array allocations and keeps the code clean.

COMPLEXITY AT A GLANCE

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

Core Theory — Why This Approach?

The problem reduces to finding the minimum sum of any contiguous sub‑array of length exactly K in an array of N weights. A naïve solution would recompute the sum for every possible window, leading to O(N·K) time, which quickly becomes infeasible when N and K are large (e.g., N = 10^5, K = 10^4). The optimal paradigm leverages the sliding‑window technique: after computing the sum of the first K elements, each subsequent window can be obtained in O(1) by subtracting the element that leaves the window and adding the new element that enters. This yields a linear O(N) traversal while maintaining constant auxiliary space. The sliding window is a special case of prefix‑sum optimization where the window size is fixed, allowing us to reuse previously computed information instead of recomputing from scratch.

Interview Questions on This Problem

Q1How would you modify the solution if the window size K could vary for each query, and you need to answer multiple queries efficiently?

Pre‑compute a prefix‑sum array P where P[i] = sum of weights[0..i‑1]. Then any window sum of length K starting at i is P[i+K]‑P[i] in O(1). For multiple queries you can answer each in O(1) after O(N) preprocessing.

Q2Can you solve the problem in O(N) time without using extra space beyond a few variables?

Yes. Use a running sum variable for the current window. Initialize it with the sum of the first K elements, then slide the window by subtracting weights[i‑K] and adding weights[i] while tracking the minimum; this uses only O(1) extra space.

Q3What would change if the array could contain negative weights and you were asked for the minimum *average* weight of a K‑length segment?

The average is just the sum divided by K, so the window with the minimum sum also yields the minimum average. The same sliding‑window algorithm works unchanged; you only need to divide the final minimum sum by K if the average value is required.

Examples

Example 1

Input

5 3
4 2 1 7 3

Output

7

Explanation: The array is [4, 2, 1, 7, 3] and K=3. The possible windows are: [4, 2, 1] with sum 7; [2, 1, 7] with sum 10; [1, 7, 3] with sum 11. The minimum sum is 7.

Example 2

Input

4 2
-1 5 -2 3

Output

-3

Explanation: The array is [-1, 5, -2, 3] and K=2. The windows are: [-1, 5] with sum 4; [5, -2] with sum 3; [-2, 3] with sum 1. Wait, let's re-calculate. [-1, 5] = 4. [5, -2] = 3. [-2, 3] = 1. The minimum is 1. Let me pick a better example for negative numbers. Let's use [10, -5, 2, 8] with K=2. Windows: [10, -5]=5, [-5, 2]=-3, [2, 8]=10. Min is -3. Let's use that.

Example 3

Input

4 2
10 -5 2 8

Output

-3

Explanation: The array is [10, -5, 2, 8] and K=2. The windows are: [10, -5] with sum 5; [-5, 2] with sum -3; [2, 8] with sum 10. The minimum sum is -3.

Example 4

Input

1 1
42

Output

42

Explanation: The array is [42] and K=1. There is only one window: [42] with sum 42. The minimum sum is 42.

Constraints

  • 1 <= N <= 10^5
  • 1 <= K <= N
  • -10^9 <= weights[i] <= 10^9
  • The sum of any subarray fits within a 64-bit integer.

Optimal Approach & Strategy

Use a sliding window: maintain the sum of the current K‑length segment, update it in O(1) as the window moves, and keep the smallest sum encountered.

Brute Force Approach

Compute the sum for every possible K‑length segment by iterating over all start indices and summing K elements each time.

Verified Code Solutions

JavaScript Solution
Time: O(N)
const fs=require('fs');const input=fs.readFileSync(0,'utf8').trim().split(/\s+/).map(Number);
let idx=0;const N=input[idx++];const k=input[idx++];const a=input.slice(idx,idx+N);
let sum=0;for(let i=0;i<k;i++)sum+=a[i];let minSum=sum;for(let i=k;i<N;i++){sum+=a[i]-a[i-k];if(sum<minSum)minSum=sum;}console.log(minSum);

Asked in Top Tech Interviews

ZomatoTCS

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.