You know sliding window. You know hash maps. But when you see "Longest Substring with At Most K Distinct Characters," you freeze.
How do you combine these patterns?
This guide shows you the template and when to use it.
When to Combine Both
The pattern
Use sliding window for the window, hash map for tracking window state.
When to use
Problems that need:
- ✅ Contiguous subarray/substring (sliding window)
- ✅ Track frequencies/counts (hash map)
- ✅ Condition based on distinct elements or frequencies
Common problems
- Longest substring with at most K distinct characters
- Permutation in string
- Minimum window substring
- Find all anagrams
The Universal Template
from collections import defaultdict
def slidingWindowWithMap(s, condition):
"""
Sliding window + hash map template.
Time: O(n)
Space: O(k) where k = distinct elements in window
"""
left = 0
freq = defaultdict(int) # Hash map for window state
result = 0
for right, char in enumerate(s):
# Expand: add to window
freq[char] += 1
# Shrink: while window invalid
while not is_valid(freq, condition):
freq[s[left]] -= 1
if freq[s[left]] == 0:
del freq[s[left]]
left += 1
# Update result with valid window
result = max(result, right - left + 1)
return resultKey insight: Hash map tracks what's in the window.
Example 1: Longest Substring with At Most K Distinct
Problem
Find longest substring with at most K distinct characters.
Solution
def lengthOfLongestSubstringKDistinct(s, k):
left = 0
freq = {}
max_len = 0
for right, char in enumerate(s):
# Add to window
freq[char] = freq.get(char, 0) + 1
# Shrink while too many distinct
while len(freq) > k:
freq[s[left]] -= 1
if freq[s[left]] == 0:
del freq[s[left]]
left += 1
# Update max length
max_len = max(max_len, right - left + 1)
return max_lenPattern: Window tracks substring, map tracks distinct count.
Example 2: Permutation in String
Problem
Check if s2 contains permutation of s1.
Solution
from collections import Counter
def checkInclusion(s1, s2):
if len(s1) > len(s2):
return False
s1_count = Counter(s1)
window_count = Counter(s2[:len(s1)])
if window_count == s1_count:
return True
# Slide window
for i in range(len(s1), len(s2)):
# Add new char
window_count[s2[i]] += 1
# Remove old char
left_char = s2[i - len(s1)]
window_count[left_char] -= 1
if window_count[left_char] == 0:
del window_count[left_char]
# Check if permutation
if window_count == s1_count:
return True
return FalsePattern: Fixed-size window, map compares frequencies.
Example 3: Minimum Window Substring
Problem
Find minimum window in s that contains all characters of t.
Solution
from collections import Counter
def minWindow(s, t):
if not s or not t:
return ""
need = Counter(t)
window = Counter()
have = 0
required = len(need)
left = 0
min_len = float('inf')
result = (0, 0)
for right, char in enumerate(s):
# Add to window
window[char] += 1
if char in need and window[char] == need[char]:
have += 1
# Shrink while valid
while have == required:
# Update result
if right - left + 1 < min_len:
min_len = right - left + 1
result = (left, right)
# Remove from window
window[s[left]] -= 1
if s[left] in need and window[s[left]] < need[s[left]]:
have -= 1
left += 1
return s[result[0]:result[1]+1] if min_len != float('inf') else ""Pattern: Shrink-to-fit window, map tracks required chars.
Common Mistakes
Mistake 1: Not removing zero counts
❌ Wrong:
window_count[left_char] -= 1
# Now window_count might have {char: 0}✅ Correct:
window_count[left_char] -= 1
if window_count[left_char] == 0:
del window_count[left_char]Why: Comparing maps with zero counts fails.
Mistake 2: Wrong window validity check
❌ Wrong:
while freq[char] > k: # Wrong condition✅ Correct:
while len(freq) > k: # Check distinct countSummary
Combining hash map + sliding window:
- Window: tracks range
- Map: tracks state (frequencies, distinct count)
The template:
freq = {}
for right, char in enumerate(s):
freq[char] = freq.get(char, 0) + 1
while not valid(freq):
freq[s[left]] -= 1
if freq[s[left]] == 0:
del freq[s[left]]
left += 1
update_result()When to use:
- Contiguous substring/subarray
- Track frequencies or distinct elements
- Condition based on window state
Next steps:
- Study frequency counter pattern
- Learn the complete hash map guide
Combine patterns for powerful solutions.
Want to Practice LeetCode Smarter?
LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.
Also compatible with Edge, Brave, and Opera
