0% found this document useful (0 votes)
20 views11 pages

Sliding Window Solutions Python

Sliding window solution
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views11 pages

Sliding Window Solutions Python

Sliding window solution
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Sliding Window Practice Problems — Full Python Solutions

1. Maximum Sum Subarray of Size K


Find the maximum sum of any subarray of size K.
def max_sum_subarray(arr, k):
if not arr or k <= 0 or k > len(arr):
return 0
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

# Example
# print(max_sum_subarray([2,1,5,1,3,2], 3)) # 9

2. First Negative Number in Every Window


Print the first negative number in every window of size K (0 if none).
from collections import deque

def first_negative_in_windows(arr, k):


q = deque()
res = []
for i, val in enumerate(arr):
if val < 0:
q.append(i)
# remove indices out of window
if q and q[0] <= i - k:
q.popleft()
if i >= k - 1:
res.append(arr[q[0]] if q else 0)
return res

# Example
# print(first_negative_in_windows([12,-1,-7,8,15,30,16,28], 3)) # [-1,-1,-7,0,0,0]

3. Count Occurrences of Anagrams (fixed length)


Count how many substrings of length K are anagrams of a given string.
from collections import Counter

def count_anagram_occurrences(text, pattern):


k = len(pattern)
if k > len(text): return 0
pat_count = Counter(pattern)
win_count = Counter(text[:k])
matches = 1 if win_count == pat_count else 0
for i in range(k, len(text)):
win_count[text[i]] += 1
start_char = text[i-k]
win_count[start_char] -= 1
if win_count[start_char] == 0:
del win_count[start_char]
if win_count == pat_count:
matches += 1
return matches

# Example
# print(count_anagram_occurrences('cbaebabacd','abc')) # 2

4. Average of Subarrays of Size K


Return average of all contiguous subarrays of size K.
def averages_of_subarrays(arr, k):
n = len(arr)
if k <= 0 or k > n: return []
res = []
window_sum = sum(arr[:k])
res.append(window_sum / k)
for i in range(k, n):
window_sum += arr[i] - arr[i-k]
res.append(window_sum / k)
return res

# Example
# print(averages_of_subarrays([1,3,2,6,-1,4,1,8,2], 5))

5. Check Subarray with Sum = K (fixed size)


Check if there exists a subarray of size K with sum exactly equal to given value.
def has_subarray_with_sum_k(arr, k, target):
if k <= 0 or k > len(arr): return False
window_sum = sum(arr[:k])
if window_sum == target: return True
for i in range(k, len(arr)):
window_sum += arr[i] - arr[i-k]
if window_sum == target:
return True
return False

# Example
# print(has_subarray_with_sum_k([1,2,3,4,5], 2, 5)) # True (2+3)

6. Find All Anagrams in String (start indices)


Find start indices of anagrams of pattern in text.
def find_anagrams(s, p):
from collections import Counter
k = len(p)
if k > len(s): return []
p_count = Counter(p)
s_count = Counter(s[:k])
res = []
if s_count == p_count:
res.append(0)
for i in range(k, len(s)):
s_count[s[i]] += 1
s_count[s[i-k]] -= 1
if s_count[s[i-k]] == 0:
del s_count[s[i-k]]
if s_count == p_count:
res.append(i-k+1)
return res

# Example
# print(find_anagrams('cbaebabacd','abc')) # [0,6]

7. Number of Subarrays of Size K with Distinct Elements


Count subarrays of size K having all distinct elements.
def count_distinct_subarrays_size_k(arr, k):
from collections import defaultdict
if k > len(arr): return 0
freq = defaultdict(int)
distinct = 0
res = 0
for i, val in enumerate(arr):
if freq[val] == 0:
distinct += 1
freq[val] += 1
if i >= k:
left = arr[i-k]
freq[left] -= 1
if freq[left] == 0:
distinct -= 1
if i >= k-1 and distinct == k:
res += 1
return res

# Example
# print(count_distinct_subarrays_size_k([1,2,1,3,4,2,3], 3))

8. Maximum of Each Window of Size K


Find the maximum element in every window of size K.
from collections import deque

def max_in_sliding_window(arr, k):


if not arr or k <= 0: return []
q = deque() # stores indices, decreasing values
res = []
for i, val in enumerate(arr):
while q and arr[q[-1]] <= val:
q.pop()
q.append(i)
if q[0] == i - k:
q.popleft()
if i >= k-1:
res.append(arr[q[0]])
return res
# Example
# print(max_in_sliding_window([1,3,-1,-3,5,3,6,7], 3)) # [3,3,5,5,6,7]

9. Minimum of Each Window of Size K


Find the minimum element in every window of size K.
from collections import deque

def min_in_sliding_window(arr, k):


if not arr or k <= 0: return []
q = deque()
res = []
for i, val in enumerate(arr):
while q and arr[q[-1]] >= val:
q.pop()
q.append(i)
if q[0] == i - k:
q.popleft()
if i >= k-1:
res.append(arr[q[0]])
return res

# Example
# print(min_in_sliding_window([2,1,3,4,6,3,8,9,10,12,56], 4))

10. Substrings of Fixed Length with K Distinct Characters


Count substrings of length K that contain exactly K distinct characters.
def substrings_k_distinct_chars(s, k):
from collections import defaultdict
n = len(s)
if k > n: return 0
freq = defaultdict(int)
distinct = 0
res = 0
for i, ch in enumerate(s):
if freq[ch] == 0:
distinct += 1
freq[ch] += 1
if i >= k:
left = s[i-k]
freq[left] -= 1
if freq[left] == 0:
distinct -= 1
if i >= k-1 and distinct == k:
res += 1
return res

# Example
# print(substrings_k_distinct_chars('abcabc', 3)) # 4
11. Longest Substring Without Repeating Characters
Find the length of longest substring with unique characters.
def length_of_longest_substring(s):
last_index = {}
start = 0
max_len = 0
for i, ch in enumerate(s):
if ch in last_index and last_index[ch] >= start:
start = last_index[ch] + 1
last_index[ch] = i
max_len = max(max_len, i - start + 1)
return max_len

# Example
# print(length_of_longest_substring('abcabcbb')) # 3

12. Smallest Subarray with Sum ≥ Target


Find minimum length subarray with sum ≥ target.
def min_subarray_len(target, arr):
left = 0
curr_sum = 0
min_len = float('inf')
for right, val in enumerate(arr):
curr_sum += val
while curr_sum >= target:
min_len = min(min_len, right-left+1)
curr_sum -= arr[left]
left += 1
return 0 if min_len == float('inf') else min_len

# Example
# print(min_subarray_len(7, [2,3,1,2,4,3])) # 2

13. Max Consecutive Ones with At Most K Zero Flips


Find max consecutive 1s if you can flip at most K zeros.
def longest_ones_with_k_flips(arr, k):
left = 0
zeros = 0
max_len = 0
for right, val in enumerate(arr):
if val == 0:
zeros += 1
while zeros > k:
if arr[left] == 0:
zeros -= 1
left += 1
max_len = max(max_len, right-left+1)
return max_len

# Example
# print(longest_ones_with_k_flips([1,1,0,0,1,1,1,0,1], 2)) # 7
14. Longest Substring with At Most K Distinct Characters
Find length of longest substring with at most K distinct chars.
def longest_substring_at_most_k_distinct(s, k):
from collections import defaultdict
freq = defaultdict(int)
left = 0
distinct = 0
max_len = 0
for right, ch in enumerate(s):
if freq[ch] == 0:
distinct += 1
freq[ch] += 1
while distinct > k:
freq[s[left]] -= 1
if freq[s[left]] == 0:
distinct -= 1
left += 1
max_len = max(max_len, right-left+1)
return max_len

# Example
# print(longest_substring_at_most_k_distinct('eceba', 2)) # 3

15. Longest Substring with Exactly K Distinct Characters


Find longest substring with exactly K distinct characters.
def longest_substring_exactly_k_distinct(s, k):
# Use helper returning longest with at most K, then subtract at most K-1
def at_most_k(k_local):
from collections import defaultdict
freq = defaultdict(int)
left = 0
distinct = 0
res = 0
for right, ch in enumerate(s):
if freq[ch] == 0:
distinct += 1
freq[ch] += 1
while distinct > k_local:
freq[s[left]] -= 1
if freq[s[left]] == 0:
distinct -= 1
left += 1
res = max(res, right-left+1)
return res
return at_most_k(k) - at_most_k(k-1)

# Example
# print(longest_substring_exactly_k_distinct('aabacbebebe', 3))

16. Permutation in String


Check if s2 contains a permutation of s1.
from collections import Counter
def check_inclusion(s1, s2):
k = len(s1)
if k > len(s2): return False
s1c = Counter(s1)
win = Counter(s2[:k])
if win == s1c: return True
for i in range(k, len(s2)):
win[s2[i]] += 1
win[s2[i-k]] -= 1
if win[s2[i-k]] == 0:
del win[s2[i-k]]
if win == s1c:
return True
return False

# Example
# print(check_inclusion('ab', 'eidbaooo')) # True

17. Count Distinct Elements in Every Window of Size K


Return number of distinct elements in every window of size K.
def distinct_elements_every_window(arr, k):
from collections import defaultdict
n = len(arr)
if k > n: return []
freq = defaultdict(int)
res = []
distinct = 0
for i, val in enumerate(arr):
if freq[val] == 0:
distinct += 1
freq[val] += 1
if i >= k:
left = arr[i-k]
freq[left] -= 1
if freq[left] == 0:
distinct -= 1
if i >= k-1:
res.append(distinct)
return res

# Example
# print(distinct_elements_every_window([1,2,1,3,4,2,3], 4)) # [3,4,4,3]

18. Maximum Sum Subarray with Size ≤ K


Find maximum sum subarray with length at most K.
def max_sum_at_most_k(arr, k):
# sliding window + prefix sums to handle variable length up to k
n = len(arr)
max_sum = float('-inf')
window_sum = 0
left = 0
for right in range(n):
window_sum += arr[right]
# shrink if size > k
if right - left + 1 > k:
window_sum -= arr[left]
left += 1
max_sum = max(max_sum, window_sum)
return max_sum

# Example
# print(max_sum_at_most_k([1,-2,3,4,-1,2], 3))

19. Longest Subarray with Sum ≤ K


Find length of longest subarray with sum <= K (non-negative nums assumed for sliding window to work).
def longest_subarray_sum_at_most_k(arr, k):
# Works correctly if array has non-negative numbers.
left = 0
curr = 0
max_len = 0
for right, val in enumerate(arr):
curr += val
while curr > k and left <= right:
curr -= arr[left]
left += 1
max_len = max(max_len, right-left+1)
return max_len

# Example
# print(longest_subarray_sum_at_most_k([1,2,1,0,1,1], 4))

20. Max Fruits into Baskets (Longest with ≤2 distinct)


Find longest subarray with at most 2 distinct fruits.
def total_fruit(fruits):
from collections import defaultdict
freq = defaultdict(int)
left = 0
max_len = 0
distinct = 0
for right, f in enumerate(fruits):
if freq[f] == 0:
distinct += 1
freq[f] += 1
while distinct > 2:
freq[fruits[left]] -= 1
if freq[fruits[left]] == 0:
distinct -= 1
left += 1
max_len = max(max_len, right-left+1)
return max_len

# Example
# print(total_fruit([1,2,1]))
21. Minimum Window Substring
Find the smallest substring of s containing all characters of t.
from collections import Counter

def min_window(s, t):


if not t or not s:
return ""
need = Counter(t)
missing = len(t)
left = start = end = 0
for right, ch in enumerate(s, 1): # right is 1-based length
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0:
if end == 0 or right - left < end - start:
start, end = left, right
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1
left += 1
return s[start:end]

# Example
# print(min_window('ADOBECODEBANC','ABC')) # 'BANC'

22. Substring with Concatenation of All Words


Find starting indices of substring in s that is concatenation of all words in list.
from collections import Counter

def find_substring_concatenation(s, words):


if not s or not words: return []
word_len = len(words[0])
total_len = word_len * len(words)
word_count = Counter(words)
res = []
for i in range(word_len):
left = i
curr_count = Counter()
for j in range(i, len(s)-word_len+1, word_len):
word = s[j:j+word_len]
if word in word_count:
curr_count[word] += 1
while curr_count[word] > word_count[word]:
left_word = s[left:left+word_len]
curr_count[left_word] -= 1
left += word_len
if j + word_len - left == total_len:
res.append(left)
else:
curr_count.clear()
left = j + word_len
return res

# Example
# print(find_substring_concatenation('barfoothefoobarman', ['foo','bar'])) # [0,9]

23. Longest Subarray with Equal 0s and 1s


Find longest subarray with equal number of 0s and 1s.
def find_max_length_equal_01(nums):
# convert 0 to -1 and find longest subarray with prefix sum repeated
prefix = 0
seen = {0:-1}
max_len = 0
for i, v in enumerate(nums):
prefix += 1 if v == 1 else -1
if prefix in seen:
max_len = max(max_len, i - seen[prefix])
else:
seen[prefix] = i
return max_len

# Example
# print(find_max_length_equal_01([0,1])) # 2

24. Max Sliding Window Median


Find median of each window of size K.
import bisect

def median_sliding_window(nums, k):


# simple O(n*k) using sorted list with bisect for clarity (not optimal)
window = sorted(nums[:k])
res = []
for i in range(k, len(nums)+1):
# median
if k % 2 == 1:
res.append(window[k//2])
else:
res.append((window[k//2 - 1] + window[k//2]) / 2)
if i == len(nums):
break
# remove nums[i-k], insert nums[i]
old = nums[i-k]
idx = bisect.bisect_left(window, old)
window.pop(idx)
bisect.insort(window, nums[i])
return res

# Example
# print(median_sliding_window([1,3,-1,-3,5,3,6,7], 3))

25. Longest Substring with At Most K Repeating Characters


Find longest substring where no char repeats more than K times.
def longest_substring_no_more_than_k_repeats(s, k):
from collections import defaultdict
freq = defaultdict(int)
left = 0
max_len = 0
for right, ch in enumerate(s):
freq[ch] += 1
while freq[ch] > k:
freq[s[left]] -= 1
left += 1
max_len = max(max_len, right-left+1)
return max_len

# Example
# print(longest_substring_no_more_than_k_repeats('aaabb', 2))

You might also like