-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path06_SlidingWindowWithMap.cpp
More file actions
347 lines (267 loc) · 11 KB
/
Copy path06_SlidingWindowWithMap.cpp
File metadata and controls
347 lines (267 loc) · 11 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
/*
================================================================================
SLIDING WINDOW WITH HASHMAP / FREQUENCY COUNTING
================================================================================
Track element frequencies within the window using HashMap/array.
Essential for problems involving:
- Distinct characters/elements
- Anagram matching
- Substring conditions
Time: O(n) | Space: O(k) where k = unique elements
================================================================================
*/
#include <bits/stdc++.h>
using namespace std;
/*
PROBLEM 1: Subarrays with K Different Integers (LeetCode 992)
─────────────────────────────────────────────────────────────
Count subarrays with exactly k distinct integers.
Input: nums = [1,2,1,2,3], k = 2
Output: 7 ([1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2])
Key Insight: exactly(k) = atMost(k) - atMost(k-1)
Time: O(n) | Space: O(k)
*/
int atMostKDistinct(vector<int>& nums, int k) {
unordered_map<int, int> freq;
int left = 0, count = 0;
for (int right = 0; right < nums.size(); right++) {
freq[nums[right]]++;
while (freq.size() > k) {
freq[nums[left]]--;
if (freq[nums[left]] == 0) freq.erase(nums[left]);
left++;
}
// All subarrays ending at right with at most k distinct
count += right - left + 1;
}
return count;
}
int subarraysWithKDistinct(vector<int>& nums, int k) {
return atMostKDistinct(nums, k) - atMostKDistinct(nums, k - 1);
}
/*
PROBLEM 2: Count Number of Nice Subarrays (LeetCode 1248)
─────────────────────────────────────────────────────────
Count subarrays with exactly k odd numbers.
Input: nums = [1,1,2,1,1], k = 3
Output: 2
Approach: Same as above - exactly(k) = atMost(k) - atMost(k-1)
Time: O(n) | Space: O(1)
*/
int atMostKOdd(vector<int>& nums, int k) {
int left = 0, count = 0, oddCount = 0;
for (int right = 0; right < nums.size(); right++) {
if (nums[right] % 2 == 1) oddCount++;
while (oddCount > k) {
if (nums[left] % 2 == 1) oddCount--;
left++;
}
count += right - left + 1;
}
return count;
}
int numberOfSubarrays(vector<int>& nums, int k) {
return atMostKOdd(nums, k) - atMostKOdd(nums, k - 1);
}
/*
PROBLEM 3: Longest Substring with At Least K Repeating Chars (LeetCode 395)
───────────────────────────────────────────────────────────────────────────
Find longest substring where every character appears at least k times.
Input: s = "aaabb", k = 3
Output: 3 ("aaa")
Approach: Try each unique character count (1 to 26) and find longest
Time: O(26 * n) = O(n) | Space: O(26) = O(1)
*/
int longestSubstring(string s, int k) {
int maxLen = 0;
// Try each number of unique characters
for (int uniqueTarget = 1; uniqueTarget <= 26; uniqueTarget++) {
vector<int> freq(26, 0);
int left = 0, uniqueCount = 0, countAtLeastK = 0;
for (int right = 0; right < s.size(); right++) {
int idx = s[right] - 'a';
if (freq[idx] == 0) uniqueCount++;
freq[idx]++;
if (freq[idx] == k) countAtLeastK++;
// Shrink while more unique than target
while (uniqueCount > uniqueTarget) {
int leftIdx = s[left] - 'a';
if (freq[leftIdx] == k) countAtLeastK--;
freq[leftIdx]--;
if (freq[leftIdx] == 0) uniqueCount--;
left++;
}
// All unique chars appear at least k times
if (uniqueCount == uniqueTarget && countAtLeastK == uniqueCount) {
maxLen = max(maxLen, right - left + 1);
}
}
}
return maxLen;
}
/*
PROBLEM 4: Frequency of Most Frequent Element (LeetCode 1838)
─────────────────────────────────────────────────────────────
You can increment elements. Return max frequency achievable with k increments.
Input: nums = [1,2,4], k = 5
Output: 3 (increment 1,2 to 4)
Approach: Sort, slide window, check if can make all equal to rightmost
Time: O(n log n) | Space: O(1)
*/
int maxFrequency(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int left = 0, maxFreq = 0;
long long sum = 0;
for (int right = 0; right < nums.size(); right++) {
sum += nums[right];
// Cost to make all elements = nums[right]
// Cost = nums[right] * windowSize - sum
while ((long long)nums[right] * (right - left + 1) - sum > k) {
sum -= nums[left];
left++;
}
maxFreq = max(maxFreq, right - left + 1);
}
return maxFreq;
}
/*
PROBLEM 5: Maximum Number of Occurrences of Substring (LeetCode 1297)
─────────────────────────────────────────────────────────────────────
Find max occurrences of any substring with:
- Length between minSize and maxSize
- At most maxLetters distinct letters
Key Insight: Only need to check minSize (larger has <= occurrences)
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2 ("aab" appears 2 times)
Time: O(n * minSize) | Space: O(n)
*/
int maxFreq(string s, int maxLetters, int minSize, int maxSize) {
unordered_map<string, int> count;
unordered_map<char, int> freq;
int maxOccur = 0;
for (int i = 0; i < s.size(); i++) {
freq[s[i]]++;
if (i >= minSize) {
freq[s[i - minSize]]--;
if (freq[s[i - minSize]] == 0) freq.erase(s[i - minSize]);
}
if (i >= minSize - 1 && freq.size() <= maxLetters) {
string sub = s.substr(i - minSize + 1, minSize);
count[sub]++;
maxOccur = max(maxOccur, count[sub]);
}
}
return maxOccur;
}
/*
PROBLEM 6: K-Beauty of a Number (LeetCode 2269)
───────────────────────────────────────────────
Count divisors of n from its substrings of length k.
Input: num = 240, k = 2
Output: 2 (24 and 40 divide 240)
Time: O(n) where n = digits | Space: O(1)
*/
int divisorSubstrings(int num, int k) {
string s = to_string(num);
int count = 0;
for (int i = 0; i <= (int)s.size() - k; i++) {
int sub = stoi(s.substr(i, k));
if (sub != 0 && num % sub == 0) count++;
}
return count;
}
/*
PROBLEM 7: Distinct Numbers in Each Subarray (Count subarrays)
──────────────────────────────────────────────────────────────
Count subarrays where all elements are distinct.
Approach: For each right, find leftmost left where all distinct.
Count = sum of (right - left + 1) for each right
Time: O(n) | Space: O(n)
*/
long long countDistinctSubarrays(vector<int>& nums) {
unordered_map<int, int> lastSeen;
long long count = 0;
int left = 0;
for (int right = 0; right < nums.size(); right++) {
if (lastSeen.count(nums[right]) && lastSeen[nums[right]] >= left) {
left = lastSeen[nums[right]] + 1;
}
lastSeen[nums[right]] = right;
count += right - left + 1;
}
return count;
}
/*
PROBLEM 8: Substring with Concatenation of All Words (LeetCode 30)
──────────────────────────────────────────────────────────────────
Find starting indices of substrings that are concatenation of all words.
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0, 9]
Time: O(n * wordLen) | Space: O(words.size())
*/
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> result;
if (words.empty() || s.empty()) return result;
int wordLen = words[0].size();
int wordCount = words.size();
int totalLen = wordLen * wordCount;
unordered_map<string, int> wordFreq;
for (const string& w : words) wordFreq[w]++;
// Start at each position within wordLen
for (int i = 0; i < wordLen; i++) {
unordered_map<string, int> seen;
int left = i, count = 0;
for (int right = i; right <= (int)s.size() - wordLen; right += wordLen) {
string word = s.substr(right, wordLen);
if (wordFreq.count(word)) {
seen[word]++;
count++;
while (seen[word] > wordFreq[word]) {
string leftWord = s.substr(left, wordLen);
seen[leftWord]--;
count--;
left += wordLen;
}
if (count == wordCount) {
result.push_back(left);
}
} else {
seen.clear();
count = 0;
left = right + wordLen;
}
}
}
return result;
}
// ============================================================================
// MAIN
// ============================================================================
int main() {
cout << "=== Sliding Window with HashMap ===\n\n";
// 1. Subarrays with K Different Integers
vector<int> arr1 = {1,2,1,2,3};
cout << "1. Subarrays with 2 distinct: " << subarraysWithKDistinct(arr1, 2) << "\n";
// 2. Nice Subarrays
vector<int> arr2 = {1,1,2,1,1};
cout << "2. Nice subarrays (k=3): " << numberOfSubarrays(arr2, 3) << "\n";
// 3. Longest Substring with K Repeating
cout << "3. Longest with >= 3 repeat: " << longestSubstring("aaabb", 3) << "\n";
// 4. Max Frequency
vector<int> arr4 = {1,2,4};
cout << "4. Max frequency (k=5): " << maxFrequency(arr4, 5) << "\n";
return 0;
}
/*
================================================================================
SUMMARY
================================================================================
Key Technique: exactly(k) = atMost(k) - atMost(k-1)
This is useful when finding subarrays with EXACTLY some property.
Convert to "at most" which is easier to solve with sliding window.
Common patterns:
1. Track frequency map as window slides
2. Track count of elements satisfying some property
3. Use two pointers with hash map for constraint checking
================================================================================
*/