Return true if some contiguous subarray of exactly length k sums to target.
subarrayTargetSum(nums, k, target)
Input format: nums | k | target.
[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
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.
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.
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.
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.
def subarray_target_sum(nums, k, target):
total = sum(nums[:k])
if total == target:
return True
for right in range(k, len(nums)):
total += nums[right] - nums[right - k]
if total == target:
return True
return False
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.