In Parts 1–3, every sliding window problem followed a single template: you were given a window size k, you maintained a running sum or count, and you slid one step at a time. The only variation was the evaluation logic — track the max, count matches, or maintain a monotonic deque. The window itself was always dumb: it just held a number.
Starting with this post, the pattern evolves. The state inside the window gets richer. Instead of a single integer (sum, count), the window now tracks a full frequency distribution or a sorted data structure. The window still slides the same way — add one element, remove one element — but the cost and complexity of each update step goes up. Comparing two frequency maps is different from comparing two integers. Maintaining two balanced BSTs is different from maintaining a running sum.
The window size is still fixed. The mechanics are still “add one, remove one.” What changes is what you’re carrying inside the window and what it costs to maintain it.
The Frequency Map Pattern
The first two problems both ask a version of the same question: does some substring of a longer string contain exactly the same characters (in any order) as a target string? In other words, is any window an anagram?
The brute-force approach would generate all permutations of the target string and check each one — factorial time, completely impractical. The key insight is that two strings are anagrams if and only if they have identical character frequencies. So instead of comparing character orderings, we compare frequency maps.
The window state is now an unordered_map of character counts. As the window slides, we decrement the count for the outgoing character and increment the count for the incoming character. At each position, we check if the window’s frequency map matches the target’s frequency map.
Since the input is limited to 26 lowercase English letters, each map has at most 26 entries. Comparing two maps is effectively O(1), so the overall time remains O(n).
One important implementation detail: when a character’s count drops to zero, erase it from the map entirely. The map equality operator checks all key-value pairs, so a key with value 0 would cause a false mismatch against a map that simply doesn’t contain that key.
Problem 9: Permutation in String (LC 567)
Difficulty: Medium
Problem: Given two strings s1 and s2, return true if s2 contains a permutation of s1.
Solution (C++)
cpp
class Solution {
public:
bool checkInclusion(string s1, string s2) {
if (s1.size() > s2.size()) {
return false;
}
unordered_map<char, int> s1Freq;
for (char c : s1) {
++s1Freq[c];
}
// fill the first window in a separate loop
unordered_map<char, int> s2Freq;
for (int i = 0; i < s1.size(); ++i) {
++s2Freq[s2[i]];
}
if (s1Freq == s2Freq) {
return true;
}
for (int i = s1.size(); i < s2.size(); ++i) {
// remove old char that is out of window
char oow = s2[i-s1.size()];
--s2Freq[oow];
if (!s2Freq[oow]) {
s2Freq.erase(oow);
}
// add new char that is part of the window now
++s2Freq[s2[i]];
if (s1Freq == s2Freq) {
return true;
}
}
return false;
}
};
How It Works
Build a frequency map for s1 once. Initialize a frequency map for the first window (first s1.size() characters of s2). Then slide: decrement the outgoing character, erase if zero, increment the incoming character, and compare maps. Return true on the first match.
The window size is fixed at s1.size(). The mechanics (add one, remove one) are the same as Part 1. What’s new is that the state is a map and the evaluation is a map comparison instead of a numeric comparison.
Time: O(n) where n = length of s2 Space: O(1) — maps have at most 26 entries
Problem 10: Find All Anagrams in a String (LC 438)
Difficulty: Medium
Problem: Given two strings s and p, return an array of all start indices of p’s anagrams in s.
Key Insight: This is LC 567 with one change: instead of returning true on the first match, collect all matching starting indices.
Solution (C++)
cpp
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
unordered_map<char, int> sFreq;
unordered_map<char, int> pFreq;
for (size_t i = 0; i < p.size(); ++i) {
++sFreq[s[i]];
++pFreq[p[i]];
}
vector<int> result;
if (sFreq == pFreq) {
result.push_back(0);
}
for (size_t i = p.size(); i < s.size(); ++i) {
if (!--sFreq[s[i-p.size()]]) {
sFreq.erase(s[i-p.size()]);
}
++sFreq[s[i]];
if (sFreq == pFreq) {
result.push_back(i-p.size()+1);
}
}
return result;
}
};
What Changed from LC 567?
Almost nothing. The sliding window logic is identical. The only difference is pushing the starting index (i – p.size() + 1) into a result vector instead of returning true, and continuing through the entire string instead of stopping at the first match.
This pair of problems is a good illustration of how recognizing the pattern pays off: once you solve one, the other takes under a minute.
Time: O(n) Space: O(1)
From Frequency Maps to Sorted Structures
The next problem takes the “complex window state” idea to its extreme. Instead of tracking character frequencies, we need to track the median of the window — which requires maintaining sorted order among all elements.
You might think a heap would work (the classic two-heap median trick), but standard heaps only support inserting and removing the top element. When the window slides, the outgoing element could be anywhere in the heap — not just the top. You can’t efficiently remove it.
The solution uses C++’s multiset, which is a balanced binary search tree. It gives O(log k) insertion, O(log k) deletion of any element by iterator, and ordered traversal. It acts like a heap that also supports arbitrary removal — exactly what we need for a sliding window that must maintain sorted order.
Problem 11: Sliding Window Median (LC 480)
Difficulty: Hard
Problem: Given an integer array nums and an integer k, return the median of each sliding window of size k.
The Two-Multiset Approach
Split the window into two halves using two multisets:
- A “maxHeap” (lower half) — we read its largest element via prev(end())
- A “minHeap” (upper half) — we read its smallest element via begin()
The maxHeap always has equal or one more element than the minHeap. This way:
- Odd k: the median is the largest element in the maxHeap
- Even k: the median is the average of the maxHeap’s largest and minHeap’s smallest
Insertion (updateHeap): Always insert into the maxHeap first, then move its largest element to the minHeap. If the minHeap becomes larger, move its smallest element back. This guarantees balance.
Removal (sliding the window): Find the outgoing element in whichever set contains it, erase it by iterator (not by value — erasing by value on a multiset removes all duplicates), then insert the new element through the normal updateHeap path.
Solution (C++)
cpp
class Solution {
public:
void updateHeap(multiset<int> &maxHeap, multiset<int> &minHeap, int num) {
maxHeap.insert(num);
auto it = prev(maxHeap.end());
int largest = *it;
maxHeap.erase(it);
minHeap.insert(largest);
if (minHeap.size() > maxHeap.size()) {
it = begin(minHeap);
maxHeap.insert(*it);
minHeap.erase(it);
}
}
double findMedian(const multiset<int> &maxHeap, const multiset<int> &minHeap) {
int rhs = *prev(maxHeap.end());
if (maxHeap.size() > minHeap.size()) {
return rhs;
}
int lhs = *minHeap.begin();
return ((double)lhs + rhs) / 2;
}
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
multiset<int> maxHeap;
multiset<int> minHeap;
// fill out the first window
for (int i = 0; i < k; ++i) {
updateHeap(maxHeap, minHeap, nums[i]);
}
vector<double> medians = {findMedian(maxHeap, minHeap)};
// starting from next window, update BST
for (size_t i = k; i < nums.size(); ++i) {
auto it = maxHeap.find(nums[i-k]);
if (it != maxHeap.end()) {
maxHeap.erase(it);
} else {
it = minHeap.find(nums[i-k]);
minHeap.erase(it);
}
updateHeap(maxHeap, minHeap, nums[i]);
medians.push_back(findMedian(maxHeap, minHeap));
}
return medians;
}
};
Complexity
Each slide involves one find + erase (O(log k)), one updateHeap with potential rebalance (O(log k)), and one findMedian (O(1)). Total: O(n log k).
Compare this to the O(nk) brute force of sorting each window, or the O(nk) of using a regular heap with lazy deletion. The multiset approach is clean and efficient.
Time: O(n log k) Space: O(k)
Pattern Summary
All three problems still use a fixed-size window that slides one step at a time. What changed from Parts 1–3 is the weight of each step:
| Problem | Window State | Update Cost | Evaluation Cost |
|---|---|---|---|
| Parts 1–3 problems | Integer (sum/count) | O(1) | O(1) |
| Permutation / Anagrams | Frequency map | O(1) | O(1) with 26-char alphabet |
| Sliding Window Median | Two balanced BSTs | O(log k) | O(1) |
The sliding window template didn’t change. The data structure inside the window got heavier.
In Part 5, we tackle a different kind of shift: variable-size windows, where there is no fixed k and the window expands and contracts based on a condition.