LeetCopilot Logo
LeetCopilot
LeetCode Pattern/Hash Map/Combining Hash Maps with Sliding Window (Template & Examples)

Combining Hash Maps with Sliding Window (Template & Examples)

LeetCopilot Team
Dec 19, 2025
5 min read
Hash MapSliding WindowPattern CombinationInterview Prep
Understand both patterns separately but struggle to combine them? Learn the template for hash map + sliding window problems.

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

python
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 result

Key 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

python
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_len

Pattern: Window tracks substring, map tracks distinct count.

Example 2: Permutation in String

Problem

Check if s2 contains permutation of s1.

Solution

python
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 False

Pattern: Fixed-size window, map compares frequencies.

Example 3: Minimum Window Substring

Problem

Find minimum window in s that contains all characters of t.

Solution

python
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:

python
window_count[left_char] -= 1
# Now window_count might have {char: 0}

Correct:

python
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:

python
while freq[char] > k:  # Wrong condition

Correct:

python
while len(freq) > k:  # Check distinct count

Summary

Combining hash map + sliding window:

  • Window: tracks range
  • Map: tracks state (frequencies, distinct count)

The template:

python
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:

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

Related Tutorials