BackmediumSliding Window Infosys

Subarray with Given Sum Solution

Problem Statement

Given an array of integers representing bandwidth usage per second, find the shortest continuous time window where the total bandwidth is at least the given target. Return 0 if impossible.

Example 1
Input
[6, 5, 4, 3, 2, 1], 8
Output
2

Explanation: Step-by-step: Given the array [6, 5, 4, 3, 2, 1] and target 8, we start a sliding window from the beginning of the array. The initial window is [6]. The sum of this window is 6, which is less than the target. We expand the window by adding the next element, 5. The new window is [6, 5]. The sum of this window is 11, which is greater than the target. However, we need to find the shortest window, so we continue expanding the window. The next element is 4, and the new window is [6, 5, 4]. The sum of this window is 15, which is greater than the target. We can stop here because the window [6, 5, 4] is the shortest window that meets the condition.

Example 2
Input
[3, 4, 5, 6, 7, 8], 12
Output
5

Explanation: Step-by-step: Given the array [3, 4, 5, 6, 7, 8] and target 12, we start a sliding window from the beginning of the array. The initial window is [3]. The sum of this window is 3, which is less than the target. We expand the window by adding the next element, 4. The new window is [3, 4]. The sum of this window is 7, which is less than the target. We continue expanding the window. The next element is 5, and the new window is [3, 4, 5]. The sum of this window is 12, which is equal to the target. We can stop here because the window [3, 4, 5] is the shortest window that meets the condition.

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= 10^4
  • 1 <= target <= 10^9
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free