Subarray Target Sum (size k)

Subarray Target Sum (size k)

Return true if some contiguous subarray of exactly length k sums to target.

subarrayTargetSum(nums, k, target)

Input format: nums | k | target.

Examples

[1, 2, 3, 4], k=2, target=5   // → true   (2+3)
[1, 2, 3, 4], k=2, target=100 // → false
[5, 5, 5], k=1, target=5      // → true

Walkthrough

Thinking it through

This asks yes/no: does any contiguous stretch of exactly k elements sum to a target? Brute force — sum each of the n possible windows independently — costs O(k) per window, O(n·k) overall, since every pair of neighboring windows shares k-1 needlessly re-summed elements.

Recognizing the fixed-window pattern

When the window slides one position right, only two elements change — one enters, one leaves. Everything else stays the same. So update the previous window's sum in constant time instead of recomputing from scratch.

Building the approach

  1. Sum the first k elements directly — your starting window.
  2. Check immediately whether this equals the target.
  3. Slide one step at a time, updating the sum: add what enters, subtract what leaves.
  4. Check the updated sum against the target after each slide — the moment it matches, return true.
  5. If you reach the end without a match, return false.

Why this beats the brute force

Maintaining the sum incrementally makes each slide O(1) instead of O(k), dropping total work from O(n·k) to O(n). Same underlying idea as maximum-sum windows, just comparing against a fixed target with an early exit.

The general principle

Whenever you evaluate some property of every fixed-size window, ask: what changes when the window slides by one? If it's "just one element enters and one leaves," you can usually turn an O(n·k) brute force into an O(n) sliding-window scan.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.