See [[https://leetcode.com/problems/subarray-sum-equals-k/description/][LC 560]]. Find the total number of continuous subarrays whose sum equals k. Solve using the brute force approach.
See [[https://leetcode.com/problems/subarray-sum-equals-k/description/][LC 560]]. Find the total number of continuous subarrays whose sum equals k. Solve optimally using prefix sum with a hash map.
See [[https://leetcode.com/problems/subarray-sum-equals-k/description/][LC 560]]. In the optimal subarray sum solution (prefix sum + hash map), why is `prefixCount[0] = 1` initialized?
See [[https://leetcode.com/problems/subarray-sums-divisible-by-k/description/][LC 974]]. Find the total number of continuous subarrays whose sum is divisible by k.
See [[https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/description/][LC 325]]. Find the maximum length of a contiguous subarray that sums to k.
See [[https://leetcode.com/problems/subarray-sum-equals-k/description/][LC 560]]. Does the prefix sum + hash map approach for "subarray sum equals k" work when the array contains negative numbers? Why?
See [[https://leetcode.com/problems/subarray-sum-equals-k/description/][LC 560]]. Can you use the sliding window technique to solve "subarray sum equals k"? When does it work?
| Count subarrays sum = K | Any integers | Prefix sum | unordered_map<sum, frequency> | O(n) |
| Longest subarray sum = K | Any integers | Prefix sum | unordered_map<sum, first_index> | O(n) |
| Shortest subarray sum ≥ K | Any integers | Prefix sum + monotonic deque | deque of indices | O(n) |
| Shortest subarray sum = K | Any integers | Prefix sum + ordered map | map<sum, last_index> | O(n log n) |
| Divisible by K | Any integers | Prefix sum + modulo | unordered_map<remainder, freq> | O(n) |
| Sum in range [lower, upper] | Any integers | Prefix sum + BST | multiset / Fenwick / segment tree | O(n log n) |
| Max circular subarray sum | Any integers | Kadane's + total - min_subarray | 2x Kadane | O(n) |
| Subarray sum with only positives | Positives only | Sliding window | Two pointers | O(n) |
| 2D matrix subarray sum = K | 2D grid | Fix rows, compress to 1D | Prefix sum on compressed row | O(n^3) |
| At most K distinct elements | Frequency constraint | Sliding window + freq map | Hash map of counts | O(n) |
| Subarray with exactly K ones | Binary array | Store indices of 1s | Vector of positions | O(n) |
| Two non-overlapping subarrays each = K | Any integers | Prefix sum + track both sides | 2 pass with prefix map | O(n) |
Core pattern: prefix[j] - prefix[i] = subarray(i+1..j). The variation changes what you store and query.
* Subarray Shortest Sum ≥ K — Monotonic Deque [algorithm:array]
:PROPERTIES:
:ANKI_NOTE_TYPE: Basic
:END:
** Front
See [[https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/description/][LC 862]]. Find the length of the shortest contiguous subarray with sum ≥ K. Works with negative numbers.
Example: nums = [84,-37,32,40,95], K = 167 → Output: 3
** Back
#+begin_src c++
intshortestSubarray(vector<int>&nums,intk){
intn=nums.size();
vector<longlong>prefix(n+1,0);
for(inti=0;i<n;i++)prefix[i+1]=prefix[i]+nums[i];
deque<int>dq;// stores indices, prefix[dq[j]] is increasing
intminLen=INT_MAX;
for(inti=0;i<=n;i++){
// If prefix[i] - prefix[dq.front()] >= K, pop front and record length
Why not hash map? Hash map can't count how many prefix sums fall in a range.
Merge sort counts (i, j) pairs where P[j] - P[i] ∈ [lower, upper] during the merge step.
* Max Circular Subarray Sum [algorithm:array]
:PROPERTIES:
:ANKI_NOTE_TYPE: Basic
:END:
** Front
See [[https://leetcode.com/problems/maximum-sum-circular-subarray/description/][LC 918]]. Find the maximum sum of a non-empty subarray in a circular array.
// If all numbers are negative, maxSum is the answer (total - minSum = 0)
returnmaxSum<0?maxSum:max(maxSum,total-minSum);
}
#+end_src
Time: O(n), Space: O(1)
Two cases:
1. Maximum subarray does NOT wrap — standard Kadane's (maxSum)
2. Maximum subarray DOES wrap — total - minSubarray (remove the minimum subarray from the middle)
Edge case: all negative → total - minSum = 0, which is wrong. Return maxSum instead.
* 2D Matrix Subarray Sum = K [algorithm:array]
:PROPERTIES:
:ANKI_NOTE_TYPE: Basic
:END:
** Front
See [[https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/description/][Submatrices Sum to Target]]. Given a 2D matrix, find the number of submatrices whose sum equals K.
Example: matrix = [[0,1,0],[1,1,1],[0,1,0]], K = 0 → Output: 4
Key idea: Fix two rows (r1, r2), compress columns between them into a 1D array.
Then the problem reduces to 1D subarray sum = K.
* Exactly K Distinct Elements with Sum = K [algorithm:array]
:PROPERTIES:
:ANKI_NOTE_TYPE: Basic
:END:
** Front
Find the length of the longest subarray with at most K distinct elements and sum = K.
** Back
#+begin_src c++
intlongestSubarray(vector<int>&nums,intk){
unordered_map<int,int>freq;
intsum=0,distinct=0,maxLen=0;
intleft=0;
for(intright=0;right<nums.size();right++){
if(freq[nums[right]]==0)distinct++;
freq[nums[right]]++;
sum+=nums[right];
// Shrink while distinct > K or sum > k
while(distinct>k||sum>k){
freq[nums[left]]--;
if(freq[nums[left]]==0)distinct--;
sum-=nums[left];
left++;
}
if(sum==k)maxLen=max(maxLen,right-left+1);
}
returnmaxLen;
}
#+end_src
Time: O(n), Space: O(min(n, K))
This combines sliding window (distinct elements constraint) with sum check.
The two constraints (distinct count + sum) make it trickier than simple sliding window.
* Binary Array — Exactly K Ones [algorithm:array]
:PROPERTIES:
:ANKI_NOTE_TYPE: Basic
:END:
** Front
See [[https://leetcode.com/problems/max-consecutive-ones-iii/description/][LC 1004]]. Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
Example: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 → Output: 6
** Back
#+begin_src c++
intlongestOnes(vector<int>&nums,intk){
intleft=0,maxLen=0;
for(intright=0;right<nums.size();right++){
if(nums[right]==0)k--;
while(k<0){
if(nums[left]==0)k++;
left++;
}
maxLen=max(maxLen,right-left+1);
}
returnmaxLen;
}
#+end_src
Time: O(n), Space: O(1)
Sliding window: expand right, count zeros. When zeros exceed k, shrink from left.
* Two Non-Overlapping Subarrays Each Sum = K [algorithm:array]
:PROPERTIES:
:ANKI_NOTE_TYPE: Basic
:END:
** Front
Find the maximum sum of two non-overlapping subarrays with lengths L and M.
Example: nums = [0,6,5,2,2,5,1,9,4], L = 1, M = 2 → Output: 20 ([9] and [6,5])