๐ Topic 2: Sliding Window (20 Problems)
Each problem is solved using the enhanced template with pseudocode, dry run, code, and explanations.
๐น 1. Maximum Sum Subarray of Size K
๐ง Problem Statement: Find the maximum sum of any contiguous subarray of size k
in the given array.
Input/Output:
- Input:
arr = [2, 1, 5, 1, 3, 2]
,k = 3
- Output:
9
โ๏ธ Pseudocode:
1. Initialize max_sum and window_sum = 0
2. Use a sliding window of size k
3. Slide the window and keep updating max_sum
๐งฐ Tools Chosen:
- Sliding Window technique
- Window sum tracking
๐งช Dry Run:
- Start with sum of first 3: 2+1+5=8 โ slide โ 1+5+1=7 โ 5+1+3=9 (max)
๐ป Code:
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i-k]
max_sum = max(max_sum, window_sum)
return max_sum
print(max_sum_subarray([2, 1, 5, 1, 3, 2], 3))
โ
Output: 9
๐ง Enhancements:
- Complexity: O(n), Space: O(1)
- Add edge case checks (if len < k)
๐น 2. First Negative Number in Every Window of Size K
๐ง Problem Statement: Given an array, print the first negative number in every window of size k
.
Input/Output:
- Input:
arr = [12, -1, -7, 8, -15, 30, 16, 28]
,k = 3
- Output:
[-1, -1, -7, -15, -15, 0]
โ๏ธ Pseudocode:
1. Use a deque to track negative numbers
2. For every window:
- Append new negative
- Pop out-of-window elements
- Append result
๐งฐ Tools Chosen:
- Deque for O(1) access
- Sliding Window
๐งช Dry Run:
- Window [12, -1, -7] โ first negative = -1 โ [-1, -1, -7…]
๐ป Code:
from collections import deque
def first_negative_k(arr, k):
q, res = deque(), []
for i in range(len(arr)):
if arr[i] < 0:
q.append(i)
if i >= k-1:
while q and q[0] < i-k+1:
q.popleft()
res.append(arr[q[0]] if q else 0)
return res
print(first_negative_k([12, -1, -7, 8, -15, 30, 16, 28], 3))
โ
Output: [-1, -1, -7, -15, -15, 0]
๐ง Enhancements:
- Use list comprehensions or numpy for speed if needed
๐ Topic 2: Sliding Window (20 Problems with Template-Based Solutions)
Problem 3: Count Occurrences of Anagrams
๐ง 0. Understand the Problem
- Problem Statement: Count how many times an anagram of
p
appears in strings
. - Input/Output:
- Input:
s = "cbaebabacd", p = "abc"
- Output: 2 (anagrams found at indices 0 and 6)
- Input:
- Constraints:
- s and p are lowercase
- Length of s โฅ length of p
- Keywords: Anagram, Frequency Map, Sliding Window
โ๏ธ 1. Write Pseudocode / Flow
Create a frequency map for p
Use a sliding window of size len(p) on s
At each step:
update the frequency of current window
compare window frequency with pattern frequency
If match, increment count
๐งฐ 2. Choose Tools
- Data Structures: HashMap (Counter from collections)
- Technique: Sliding window, Frequency comparison
๐งช 3. Dry Run with Mini Input
- s = “abcbac”, p = “abc”
- Window: “abc” โ match โ count = 1
- Window: “bcb” โ no match
- Window: “cba” โ match โ count = 2
๐ป 4. Code
from collections import Counter
def count_anagrams(s, p):
len_p = len(p)
p_count = Counter(p)
s_count = Counter()
result = 0
for i in range(len(s)):
s_count[s[i]] += 1
if i >= len_p:
s_count[s[i-len_p]] -= 1
if s_count[s[i-len_p]] == 0:
del s_count[s[i-len_p]]
if s_count == p_count:
result += 1
return result
print(count_anagrams("cbaebabacd", "abc"))
โ 5. Test & Debug
- Add print statements for sliding window and counters
- Edge case: s = “aaaaa”, p = “a” โ 5 matches
๐ง Optional Enhancements
- Use
==
for Counter comparison - Time: O(n), Space: O(1) since 26 letters only
Problem 4: Longest Substring with K Distinct Characters
๐ง 0. Understand the Problem
- Problem Statement: Find the length of the longest substring with exactly K distinct characters.
- Input: s = “eceba”, k = 2 โ Output: 3 (“ece”)
- Constraints: 1 โค s.length โค 5 * 10^4
- Keywords: Substring, Distinct Count, Sliding Window
โ๏ธ 1. Write Pseudocode
Initialize left pointer, hashmap to store character counts
Expand right pointer
add character to hashmap
if size > K, shrink window from left
Track max length
๐งฐ 2. Choose Tools
- HashMap for char counts
- Sliding window technique
๐งช 3. Dry Run
- s = “abcba”, k=2
- “ab” โ valid
- “abc” โ shrink to “bc”
- “bcb” โ valid, max = 3
๐ป 4. Code
def longest_k_distinct(s, k):
from collections import defaultdict
left = 0
count = defaultdict(int)
max_len = 0
for right in range(len(s)):
count[s[right]] += 1
while len(count) > k:
count[s[left]] -= 1
if count[s[left]] == 0:
del count[s[left]]
left += 1
max_len = max(max_len, right - left + 1)
return max_len
print(longest_k_distinct("eceba", 2))
โ 5. Test & Debug
- Edge case: s = “aa”, k = 1 โ Output = 2
- Use print(count) to debug shrinking
๐ง Enhancements
- Time: O(n), Space: O(k)
Problem 5: Longest Repeating Character Replacement
๐ง 0. Understand the Problem
- Problem Statement: Replace at most k characters in string s to make longest repeating character substring.
- Input: s = “ABAB”, k = 2 โ Output = 4
- Constraints: Only uppercase letters
- Keywords: Frequency, Max Replace
โ๏ธ 1. Pseudocode
Sliding window, count frequency of chars
Keep max_freq
If (window size - max_freq) > k โ shrink window
๐งฐ 2. Choose Tools
- HashMap
- Sliding window
๐ป 4. Code
def character_replacement(s, k):
from collections import defaultdict
count = defaultdict(int)
max_len = 0
max_freq = 0
left = 0
for right in range(len(s)):
count[s[right]] += 1
max_freq = max(max_freq, count[s[right]])
if (right - left + 1) - max_freq > k:
count[s[left]] -= 1
left += 1
max_len = max(max_len, right - left + 1)
return max_len
print(character_replacement("ABAB", 2))
๐ง Enhancements
- Optimize by tracking
max_freq
Problem 6: Permutation in String
๐ง 0. Understand the Problem
- Problem Statement: Check if s2 contains a permutation of s1.
- Input: s1 = “ab”, s2 = “eidbaooo” โ Output: True
- Keywords: Anagram match
โ๏ธ 1. Pseudocode
Compare frequency of s1 and current window of size len(s1)
๐ป Code
from collections import Counter
def check_inclusion(s1, s2):
len1 = len(s1)
s1_count = Counter(s1)
s2_count = Counter()
for i in range(len(s2)):
s2_count[s2[i]] += 1
if i >= len1:
s2_count[s2[i - len1]] -= 1
if s2_count[s2[i - len1]] == 0:
del s2_count[s2[i - len1]]
if s1_count == s2_count:
return True
return False
print(check_inclusion("ab", "eidbaooo"))
โ 5. Test
- Use frequency count and comparison
Leave a Reply