-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path03_PrefixWithHashMap.cpp
More file actions
411 lines (307 loc) · 13 KB
/
Copy path03_PrefixWithHashMap.cpp
File metadata and controls
411 lines (307 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*
================================================================================
PREFIX SUM + HASHMAP
================================================================================
Powerful combination for subarray problems:
- Subarray sum equals K
- Count subarrays with specific sum
- Longest subarray with target sum
Key insight: If prefix[j] - prefix[i] = K, then subarray [i+1, j] has sum K.
Store prefix sums in hashmap for O(1) lookup.
Time: O(n) | Space: O(n)
================================================================================
*/
#include <bits/stdc++.h>
using namespace std;
/*
PROBLEM 1: Subarray Sum Equals K (LeetCode 560) ⭐ GOOGLE FAVORITE
─────────────────────────────────────────────────────────────────
Count subarrays with sum equal to k.
Input: nums = [1,1,1], k = 2
Output: 2 ([1,1] appears twice)
Time: O(n) | Space: O(n)
*/
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> prefixCount;
prefixCount[0] = 1; // Empty prefix
int count = 0, prefixSum = 0;
for (int num : nums) {
prefixSum += num;
// If (prefixSum - k) exists, we found subarrays with sum k
if (prefixCount.count(prefixSum - k)) {
count += prefixCount[prefixSum - k];
}
prefixCount[prefixSum]++;
}
return count;
}
/*
PROBLEM 2: Continuous Subarray Sum (LeetCode 523)
─────────────────────────────────────────────────
Check if subarray of length >= 2 has sum divisible by k.
Key: (prefix[j] - prefix[i]) % k == 0 ⟹ prefix[j] % k == prefix[i] % k
Time: O(n) | Space: O(min(n, k))
*/
bool checkSubarraySum(vector<int>& nums, int k) {
unordered_map<int, int> remainderIndex;
remainderIndex[0] = -1; // Index before array starts
int prefixSum = 0;
for (int i = 0; i < nums.size(); i++) {
prefixSum += nums[i];
int remainder = prefixSum % k;
if (remainderIndex.count(remainder)) {
// Subarray length must be >= 2
if (i - remainderIndex[remainder] >= 2) {
return true;
}
} else {
remainderIndex[remainder] = i; // Store first occurrence
}
}
return false;
}
/*
PROBLEM 3: Subarray Sums Divisible by K (LeetCode 974)
──────────────────────────────────────────────────────
Count subarrays with sum divisible by k.
Time: O(n) | Space: O(k)
*/
int subarraysDivByK(vector<int>& nums, int k) {
unordered_map<int, int> remainderCount;
remainderCount[0] = 1;
int count = 0, prefixSum = 0;
for (int num : nums) {
prefixSum += num;
int remainder = ((prefixSum % k) + k) % k; // Handle negative
count += remainderCount[remainder];
remainderCount[remainder]++;
}
return count;
}
/*
PROBLEM 4: Longest Subarray with Sum K (Not on LeetCode)
────────────────────────────────────────────────────────
Find longest subarray with sum exactly k.
Note: For positive numbers only, sliding window works.
For any integers, use hashmap.
Time: O(n) | Space: O(n)
*/
int longestSubarraySumK(vector<int>& nums, int k) {
unordered_map<int, int> prefixIndex;
prefixIndex[0] = -1; // Before first element
int maxLen = 0, prefixSum = 0;
for (int i = 0; i < nums.size(); i++) {
prefixSum += nums[i];
if (prefixIndex.count(prefixSum - k)) {
maxLen = max(maxLen, i - prefixIndex[prefixSum - k]);
}
// Store first occurrence only (for longest)
if (!prefixIndex.count(prefixSum)) {
prefixIndex[prefixSum] = i;
}
}
return maxLen;
}
/*
PROBLEM 5: Binary Subarrays With Sum (LeetCode 930)
───────────────────────────────────────────────────
Count subarrays with sum equal to goal (binary array).
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
Time: O(n) | Space: O(n)
*/
int numSubarraysWithSum(vector<int>& nums, int goal) {
unordered_map<int, int> prefixCount;
prefixCount[0] = 1;
int count = 0, prefixSum = 0;
for (int num : nums) {
prefixSum += num;
count += prefixCount[prefixSum - goal];
prefixCount[prefixSum]++;
}
return count;
}
/*
PROBLEM 6: Count Number of Nice Subarrays (LeetCode 1248)
─────────────────────────────────────────────────────────
Count subarrays with exactly k odd numbers.
Convert: odd → 1, even → 0, then find subarrays with sum = k.
Time: O(n) | Space: O(n)
*/
int numberOfSubarrays(vector<int>& nums, int k) {
unordered_map<int, int> prefixCount;
prefixCount[0] = 1;
int count = 0, oddCount = 0;
for (int num : nums) {
oddCount += (num % 2); // 1 if odd, 0 if even
count += prefixCount[oddCount - k];
prefixCount[oddCount]++;
}
return count;
}
/*
PROBLEM 7: Longest Well-Performing Interval (LeetCode 1124)
───────────────────────────────────────────────────────────
Find longest interval where tiring days > non-tiring days.
Tiring day: hours > 8.
Convert: >8 → +1, <=8 → -1, find longest subarray with sum > 0.
Time: O(n) | Space: O(n)
*/
int longestWPI(vector<int>& hours) {
unordered_map<int, int> prefixIndex;
int maxLen = 0, prefixSum = 0;
for (int i = 0; i < hours.size(); i++) {
prefixSum += (hours[i] > 8) ? 1 : -1;
if (prefixSum > 0) {
// Entire array [0, i] is valid
maxLen = i + 1;
} else {
// Find earliest j where prefix[j] = prefixSum - 1
if (prefixIndex.count(prefixSum - 1)) {
maxLen = max(maxLen, i - prefixIndex[prefixSum - 1]);
}
}
// Store first occurrence
if (!prefixIndex.count(prefixSum)) {
prefixIndex[prefixSum] = i;
}
}
return maxLen;
}
/*
PROBLEM 8: Contiguous Array (LeetCode 525)
──────────────────────────────────────────
Longest subarray with equal 0s and 1s.
Convert: 0 → -1, find longest subarray with sum = 0.
Time: O(n) | Space: O(n)
*/
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> prefixIndex;
prefixIndex[0] = -1;
int maxLen = 0, prefixSum = 0;
for (int i = 0; i < nums.size(); i++) {
prefixSum += (nums[i] == 0) ? -1 : 1;
if (prefixIndex.count(prefixSum)) {
maxLen = max(maxLen, i - prefixIndex[prefixSum]);
} else {
prefixIndex[prefixSum] = i;
}
}
return maxLen;
}
/*
PROBLEM 9: Number of Subarrays with Bounded Maximum (LeetCode 795)
──────────────────────────────────────────────────────────────────
Count subarrays where max element is in [left, right].
Approach: count(max <= right) - count(max <= left - 1)
Time: O(n) | Space: O(1)
*/
int numSubarrayBoundedMax(vector<int>& nums, int left, int right) {
auto countAtMost = [&](int bound) {
int count = 0, current = 0;
for (int num : nums) {
current = (num <= bound) ? current + 1 : 0;
count += current;
}
return count;
};
return countAtMost(right) - countAtMost(left - 1);
}
/*
PROBLEM 10: Subarrays with K Different Integers (LeetCode 992)
──────────────────────────────────────────────────────────────
Count subarrays with exactly k distinct integers.
Approach: atMost(k) - atMost(k-1)
Time: O(n) | Space: O(n)
*/
int subarraysWithKDistinct(vector<int>& nums, int k) {
auto atMost = [&](int k) {
if (k < 0) return 0;
unordered_map<int, int> freq;
int count = 0, left = 0;
for (int right = 0; right < nums.size(); right++) {
if (freq[nums[right]] == 0) k--;
freq[nums[right]]++;
while (k < 0) {
freq[nums[left]]--;
if (freq[nums[left]] == 0) k++;
left++;
}
count += right - left + 1;
}
return count;
};
return atMost(k) - atMost(k - 1);
}
/*
PROBLEM 11: Count Subarrays Where Max Element Appears K Times (LeetCode 2962)
─────────────────────────────────────────────────────────────────────────────
Count subarrays where maximum element appears at least k times.
Time: O(n) | Space: O(1)
*/
long long countSubarrays(vector<int>& nums, int k) {
int maxVal = *max_element(nums.begin(), nums.end());
long long count = 0;
int maxCount = 0, left = 0;
for (int right = 0; right < nums.size(); right++) {
if (nums[right] == maxVal) maxCount++;
while (maxCount >= k) {
count += nums.size() - right; // All extensions are valid
if (nums[left] == maxVal) maxCount--;
left++;
}
}
return count;
}
// ============================================================================
// MAIN
// ============================================================================
int main() {
cout << "=== Prefix Sum + HashMap ===\n\n";
// Subarray Sum Equals K
vector<int> nums1 = {1, 1, 1};
cout << "1. Subarrays with sum 2: " << subarraySum(nums1, 2) << "\n";
// Continuous Subarray Sum
vector<int> nums2 = {23, 2, 4, 6, 7};
cout << "2. Has subarray divisible by 6: "
<< (checkSubarraySum(nums2, 6) ? "Yes" : "No") << "\n";
// Subarrays Divisible by K
vector<int> nums3 = {4, 5, 0, -2, -3, 1};
cout << "3. Subarrays divisible by 5: " << subarraysDivByK(nums3, 5) << "\n";
// Longest with sum K
vector<int> nums4 = {1, -1, 5, -2, 3};
cout << "4. Longest subarray sum 3: " << longestSubarraySumK(nums4, 3) << "\n";
// Contiguous Array (equal 0s and 1s)
vector<int> nums5 = {0, 1, 0};
cout << "8. Longest equal 0s and 1s: " << findMaxLength(nums5) << "\n";
// K Different Integers
vector<int> nums6 = {1, 2, 1, 2, 3};
cout << "10. Subarrays with 2 distinct: " << subarraysWithKDistinct(nums6, 2) << "\n";
return 0;
}
/*
================================================================================
SUMMARY
================================================================================
PREFIX + HASHMAP PATTERN:
─────────────────────────
map[0] = 1 (or map[0] = -1 for index)
for each element:
prefixSum += element
check if (prefixSum - target) in map
update map
+───────────────────────────────+────────────────────────────────────────────────+
| Problem | Transformation |
+───────────────────────────────+────────────────────────────────────────────────+
| Sum = K | Direct prefix sum |
| Divisible by K | Store prefix % k |
| Equal 0s and 1s | 0 → -1, sum = 0 |
| K odd numbers | odd → 1, even → 0 |
| Exactly K distinct | atMost(k) - atMost(k-1) |
| More tiring than non-tiring | >8 → +1, <=8 → -1, sum > 0 |
+───────────────────────────────+────────────────────────────────────────────────+
COUNT vs LONGEST:
- Count: map stores frequency
- Longest: map stores first occurrence index
================================================================================
*/