Loading...
Loading...
You are given an integer array nums and two integers k and maxLen. Your task is to find the total number of contiguous subarrays whose sum equals k AND whose length does not exceed maxLen.
This problem combines the classic Two Sum / prefix-sum hashing technique with a sliding window / length constraint, making it a natural extension of common interview problems.
nums — a list of integers (can include negatives)k — the target subarray summaxLen — the maximum allowed subarray length (inclusive)Return a single integer: the count of valid subarrays.
Input: nums = [1, 2, 3, -2, 2], k = 3, maxLen = 3
Output: 3
Explanation:
[1, 2] → sum = 3, length = 2 ✅[3] → sum = 3, length = 1 ✅[1, 2, 3, -2, -1] ← too long; skip[3, -2, 2] → sum = 3, length = 3 ✅
Valid subarrays: 3Input: nums = [1, -1, 1, -1], k = 0, maxLen = 2
Output: 3
Explanation:
[1, -1] at indices 0–1 ✅[-1, 1] at indices 1–2 ✅[1, -1] at indices 2–3 ✅Input: nums = [5], k = 5, maxLen = 1
Output: 1
Explanation: The single element [5] equals k and has length 1 ≤ maxLen.
prefixSum[i] = sum of nums[0..i-1]. A subarray nums[l..r] has sum = prefixSum[r+1] - prefixSum[l].k, store previously seen prefix sums. For each index r, look up how many times prefixSum[r] - k has appeared.nums[l..r] has length r - l + 1. You need r - l + 1 <= maxLen, i.e., l >= r - maxLen + 1. This means you cannot use all previous prefix sums — only those within the valid window.1 <= nums.length <= 10^4 -10^4 <= nums[i] <= 10^4 -10^7 <= k <= 10^7 1 <= maxLen <= nums.length
r, remove prefix sums that are now out of the valid window (those at index l < r - maxLen + 1).The key insight: maintain a hash map of prefix sums, but only for the indices within the valid lookback window of size maxLen.