Data Structures & Algorithms practice
Data Structures & Algorithms · Array Patterns

Sliding Window: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1The Pattern NamedEasyMust Do

A window is a contiguous segment of a sequence, written [left, right] with both ends included. Its length is right - left + 1. For items = [2, 1, 5, 1, 3, 2] and k = 3, list every window of size k and its sum, then find the largest sum of k consecutive values by brute force. Finally name the two families of window problems.

Q2Counting The Brute ForceEasy

Instrument the brute-force "largest sum of k consecutive values" so it counts every addition it performs. Print a table for several (n, k) pairs and show that the count is (n - k + 1) * k, so it grows like n * k.

Q3The Sliding SumEasyMust Do

Neighbouring windows share all but two items: one enters on the right, one leaves on the left. Write max_window_sum that keeps a running window_sum (add the entering item, subtract the leaving item) so it runs in O(n). Check it against the brute force on random inputs, then time both with n = 4,000 and k = 1,000 using a best_of(fn, repeats=3) helper (min of 3 runs).

Q4Every Window's SumEasy

Write window_sums(items, k) returning the list of all n - k + 1 window sums, left to right, in O(n). Decide and enforce the edge rules: k > n gives [], k == n gives exactly one sum, and k <= 0 raises ValueError.

Q5Averages Without DivisionEasy

Count the windows of size k whose average is at least a threshold. Prices are stored as integers in tenths (so 1 means 0.1), and the threshold t is also in tenths. Compare window_sum >= t * k so no division and no floats are involved. Then show a crafted case where the float version window_sum / k >= t gives a different answer from the truth.

Q6A Window Over A StringEasy

Find the largest number of vowels (a e i o u) in any substring of length k. Use the same add/remove step as for numbers: each character contributes 1 if it is a vowel and 0 otherwise.

Q7Distinct In Every WindowMedium

For every window of size k, return how many distinct values it contains. Keep a dict counts of value to number of copies in the window, and delete a key when its count reaches 0, so len(counts) means "distinct in the window". Then show the bug where zero-count keys are kept, printed beside the truth.

Q8Anagram WindowsMedium

Return every start index i where s[i:i + len(p)] is an anagram of p (same letters, same counts), for lowercase letters only. Keep two 26-slot count lists, need for p and counts for the current window, update counts as the window slides, and compare the two lists at every step. Check against a brute force that sorts each substring.

Q9The Match CounterMedium

Remove the 26-slot comparison from each step. Keep matches, the number of letters whose counts agree with need, and update it only for the one or two letters that change when a character enters or leaves. The window is an anagram exactly when matches == 26. Check it against the compare-all version, count the letter comparisons each one does, and time both with a best_of helper (min of 3 runs).

Q10Fixed Or VariableEasy

Classify eight short problem statements as fixed (the window size is given), variable (the window size is the answer, or the window grows and shrinks under a condition), or not a window. Return a dict mapping each statement to (kind, one-line reason) and print it sorted.

Q11Growing Until ValidEasy

Given a list of positive integers and a target, find the length of the shortest contiguous subarray whose sum is >= target, or 0 if no subarray qualifies. Write the naive version first: for each left, grow right one step at a time, keeping a running window_sum, and stop at the first right where the window is valid (a longer window from the same left can only be worse, so there is no reason to keep going). Count the additions it does on an input where no window ever qualifies, to see what this costs.

Q12The Grow/Shrink TemplateEasyMust Do

Solve the shortest-subarray-with-sum->= target problem (positive integers, 0 if none) in O(n) with the five-line grow/shrink template. Put the template skeleton in a comment block at the top, write the validity sentence before the code, and then check your function against the naive O(n^2) version on a few hundred seeded random inputs.

Q13Stating "Invalid" PreciselyEasyMust Do

Find the length of the longest subarray whose sum is <= k (non-negative values, k >= 0). Before any code, write the sentence # INVALID when: window_sum > k, and code the shrink loop straight from it. Then show why the sentence matters: write two near-miss versions, one whose sentence says window_sum >= k and one whose sentence says "the last element is > k", and print their wrong answers beside the correct one on the same input.

Q14Longest Versus ShortestEasy

Where the record line goes depends on what the problem asks. For a longest-valid problem, record after the shrink loop (the window is valid there). For a shortest-valid problem, the shrink loop runs while the window is valid, so you record inside it. Solve one of each side by side on the same list (longest subarray with sum <= 7, shortest subarray with sum >= 7), then move the record line to the wrong place in each and print the wrong answers.

Q15Why The Nested While Is O(n)EasyMust Do

A while inside a for looks quadratic. Instrument the longest-subarray-with-sum-<= k template to count the outer-loop steps and the inner-loop (shrink) steps, run it for n = 1,000, 2,000, 4,000 … 64,000 on seeded random data, and print the ratio of shrink steps to n. Run it once on random data and once on an input built to force heavy shrinking, and cite the movement budget from DSA Topic 4 in one sentence. Do not write a new proof.

Q16No Repeats, By Brute ForceEasy

Find the length of the longest substring (more generally, the longest run of items) with no repeated item. Write the naive version: for each left, extend right while the next item is not already in a set for this start, and stop at the first repeat. Count the inner steps on a list of all-distinct values for n = 250, 500, 1000, 2000 to see the cost.

Q17Longest Substring Without RepeatsMediumMust Do

Solve longest-substring-without-repeating-characters in O(n) with the grow/shrink template. Keep a dict counts of the characters in the window (delete a key when its count reaches 0). Open with # INVALID when: some count > 1 and note that only the character just added can be the offender. Shrink until that character's count is back to 1. Fuzz the result against a brute force on small strings over a tiny alphabet, and include the empty string.

Q18Jumping The Left EdgeMedium

A faster shrink: store the last index of each character in a dict. When text[right] was seen before, jump left straight to last[ch] + 1 instead of removing one character at a time. The jump must never move left backwards, so write left = max(left, last[ch] + 1). Implement it, then implement the broken version without max and print both next to the truth on "abba".

Q19Longest Run After k FlipsEasyMust Do

Given a list of 0s and 1s and an integer k, find the longest run of 1s you can get if you may flip at most k zeros to ones. Open with # INVALID when: zeros in window > k. Cover k = 0 (the longest existing run) and k >= the number of zeros (the whole list). Check the answer against a brute force on seeded random lists.

Q20The Case Converging Pointers MissEasy

DSA Topic 4 walked two pointers inward from the ends. That works when the answer is "what is left after trimming the ends". Here is a problem where it cannot: the longest subarray with sum <= k when the best segment touches neither end of the list. Implement a converging walk (start with the whole list and, while the sum is > k, drop the larger of the two end elements; on a tie drop the left one) and the sliding window. Print both on [1, 3, 3, 1, 2, 4] with k = 6, and say which one is right and why.

Q21Maximum Of Every Window, NaivelyEasy

Write window_maxima_naive(items, k) that returns the maximum of every window of size k, by calling max() on each slice. Raise ValueError for k <= 0 and return [] when k > len(items). Then hold n = 4,000 fixed, grow k through 1, 10, 100, 1,000 and 2,000, and print the time (min of 3 runs) next to the number of items examined. This is the baseline the next version has to beat.

Q22The Monotonic Deque, PreviewedMediumMust Do

The maximum of a window cannot be kept with a running add/subtract, because "remove the leaving item" does not tell you what the next largest is. The fix is to keep candidates: indices whose values are in decreasing order, so the front is always the maximum.

Write window_maxima(items, k) in O(n). The collections.deque is DSA Topic 11, so build the deque as a plain list dq plus a head index (dq[head:] is the live deque). Push each right at the back after popping every smaller-or-equal value; drop the front when it has left the window. Check it against max() of each slice on seeded random inputs, time it against the naive version on n = 4,000 and k = 1,000, and state the amortised argument in a comment.

Q23Why Negatives Break ItEasy

The grow/shrink template for "longest subarray with sum <= k" quietly assumes that growing a window never lowers its sum. Write longest_sum_at_most(items, k) with the template, and an honest O(n^2) longest_sum_truth. Show that the two agree on non-negative input, then search all short lists over -2..2 for the first input where they disagree and print both answers. Finally fuzz 2,000 seeded inputs with negatives and print how often the template is wrong. Name what replaces it.

Q24The Monotone ConditionEasy

The real precondition of the template is: if a window is valid, every window inside it is valid (a monotone condition). Write find_violation(valid, items) that takes a function valid(window_list) and returns the first (window, smaller_window) pair where the window is valid but a window one item shorter (dropping the left or the right end) is not, or None. Run it on seeded random lists for six conditions and print which are monotone: sum <= 5 on non-negative values, sum <= 5 with negative values, sum == 5, at most 2 distinct, max - min <= 3, and even length.

Q25The Invariant As An AssertEasy

Every variable-window answer promises: after the while loop, [left, right] is valid. Put that promise into code. Write a direct is_valid_* check for three problems (longest sum <= k on non-negatives, longest substring without repeats, longest substring with at most k distinct), call it as an assert after the while in each template, and run seeded fuzz inputs through all three. Then break one on purpose by replacing while with if, and show the assert catching it on a named input.

Q26At Most k DistinctMediumMust Do

Write longest_at_most_k_distinct(text, k): the length of the longest substring that has at most k different characters. Open with the sentence that defines invalid. Keep the counts in a dict and delete a key when its count reaches 0, so len(counts) means "distinct characters in the window". Cover k = 0 (answer 0) and an empty string, and check the template against a brute force on seeded random strings.

Q27Exactly k Distinct, LongestMedium

Write longest_exactly_k_distinct(text, k): the longest substring with exactly k different characters, or -1 if there is none. The window that is monotone is "at most k", so keep that window and record only when len(counts) == k. Then write the tempting wrong version that shrinks until the count equals k, and print both beside a brute force on "aab" with k = 2.

Q28Two Kinds OnlyEasy

A farmer walks down a row of trees (a list of fruit types) with two baskets, and each basket holds one type only. Starting anywhere, they pick one fruit from each tree going right and must stop at the first tree that would need a third type. Write longest_two_kinds(trees) returning the length of the longest run they can pick and its starting index (the leftmost run on ties). Print a step trace for one row, showing right, the new fruit, left, the window and the counts at each step.

Q29Minimum Window, NaivelyMedium

Given strings s and t, find the shortest substring of s that contains every character of t, with multiplicity (if t = "aab" the window needs two a and one b). Return "" if there is none, and the leftmost window when several have the same length. Write the baseline min_window_naive(s, t): for each start, grow to the right until the window covers t, then stop growing and try the next start. Count how many characters it examines on a bad input.

Q30Minimum Window SubstringHardMust Do

Write min_window(s, t): the shortest substring of s containing every character of t with multiplicity, "" if none, and the leftmost window on ties. This is a shortest-valid problem, so the loop flips: grow with right, then while the window is valid, record inside the loop, remove the left character and move left. Keep a need dict of outstanding counts and a missing counter so validity is an O(1) test. Fuzz it against the naive version, then time both.

Q31Repeats In The PatternMedium

The minimum-window search keeps a dict need (how many of each letter of t the window still lacks) and a counter missing (letters of t still lacking, with multiplicity). When t has repeated letters, such as "aab", there is a trap: a third a in the window is a surplus and must not reduce missing. Write min_window(s, t, guarded) so that guarded=True decrements missing only while need[ch] > 0, and guarded=False decrements it for every letter of t. Run both on s = "aaab", t = "aab" beside a brute-force min_window_truth (shortest window, leftmost on ties), and show the unguarded version over-counting. Fuzz the guarded version.

Q32Permutation In A StringEasyMust Do

Does s contain a permutation of p as a contiguous substring? A permutation of p has exactly the letters of p, so the window has a fixed size len(p). Write find_permutation(s, p) returning (found, start) where start is the first (leftmost) index, or -1. Keep two 26-slot count lists and a matches counter: the number of letters whose counts agree. When a letter enters or leaves, update matches in O(1). Cover len(p) > len(s) and an empty p. Check it against a sorted-letters brute force.

Q33Longest Repeating ReplacementHardMust Do

Given a string s of lowercase letters and an integer k, find the length of the longest substring that can be turned into a single repeated letter with at most k replacements. The cost to unify a window is length - (count of its most frequent letter). Write longest_replacement(s, k) with the comment # INVALID when: length - max_count > k, tracking max_count as a value that is never decreased when the window shrinks. Explain in comments why that stale max_count still gives the right length. Check it against a brute force.

Q34One Flip, StreamingEasy

Values arrive one at a time (a generator, not a list). Find the longest run of 1s if at most one 0 may be flipped. Write longest_one_flip(stream) that keeps only the index of the last zero and the current left edge, so the space is O(1). Compare it with a list-based variable window on random streams, and run it on a generator of 200,000 values that is never stored.

Q35Deleting Exactly OneMedium

Given a binary list, delete exactly one element, then report the length of the longest run of 1s in what is left. Write longest_after_delete(items). Use a window holding at most one zero, and note that the deleted element must come out of the length. The trap is the all-ones list: you must still delete a 1, so the answer is n - 1, not n. Raise ValueError on an empty list. Fuzz it against a brute force that tries every deletion.

Q36Counting WindowsMediumMust Do

Count the non-empty subarrays whose sum is <= k, for a list of non-negative integers. Instead of recording a best, add the number of valid windows that end at right. Write count_at_most(items, k) with the comment # INVALID when: window_sum > k. In two sentences in a comment, prove why right - left + 1 is the right amount to add. Check it against an enumeration of every subarray, and raise ValueError on a negative value.

Q37Product Less Than kMedium

Count the non-empty subarrays of a list of positive integers whose product is strictly less than k. Write count_product_below(items, k) with # INVALID when: product >= k. Remove the leaving item with //, which is exact because the product is a multiple of it. The edge case is k <= 1: every product is at least 1, so the answer is 0, and without a guard the shrink loop runs left past the end of the list. Show what the unguarded loop does. Say what a C or Java version would have to worry about that Python does not.

Q38Exactly k By SubtractionHardMust Do

Count the subarrays with exactly k distinct values. Window counting works for "at most", because at most k is monotone. "Exactly k" is not. Show the failure first: write monotone_violations(items, k) that finds a window with exactly k distinct values that contains a smaller window that does not. Show the direct template (shrink while len(counts) > k, then count) giving a wrong answer. Then fix it with exactly(items, k) = at_most(items, k) - at_most(items, k - 1). Check it against a brute force.

Q39Binary Subarrays With A SumMedium

Given a list of 0s and 1s and an integer goal, count the non-empty subarrays whose sum equals goal. sum == goal is not monotone, and zeros mean many starts give the same sum, so a shrink-then-check window undercounts; use at_most(goal) - at_most(goal - 1). Show the direct check giving the wrong count. Handle goal = 0 (the subtraction reaches at_most(-1), which is 0) and a negative goal. Check it against an enumeration, and show the count for an all-zeros list, where the answer is n * (n + 1) / 2.

Q40Exactly k Odd NumbersMedium

Count the subarrays of a list of integers that contain exactly k odd numbers. Map each value with v % 2 (Python gives 1 for a negative odd number too; in C or Java -3 % 2 == -1) and reuse at_most(k) - at_most(k - 1). Then write a one-pass version with two left edges and two odd counters, one for "at most k" and one for "at most k - 1", adding left_near - left_far per right. Show that the two versions and a brute force all agree, including k = 0.

Q41The Grumpy WindowMedium

A shop owner is grumpy on some minutes, and customers who arrive during a grumpy minute leave unhappy (they are not counted). customers[i] is how many arrive in minute i, and grumpy[i] is 1 if the owner is grumpy then, 0 if calm. The owner has one secret technique that keeps them calm for exactly m consecutive minutes (used once).

Write max_satisfied(customers, grumpy, m). The idea is to separate the always-counted part from the window part: customers in calm minutes count no matter what, so add them to a baseline once, and slide a fixed window of size m over only the extra gain customers[i] * grumpy[i]. Handle m >= len(customers) (the window is the whole day) and m == 0 (no technique), and raise ValueError for m < 0. Check it against a brute force on seeded inputs, and show the double-counting bug where the window slides over all customers and the baseline is added on top.

Q42Taking From Both EndsMedium

A row of cards has a point value on each. You must take exactly k cards, and each card comes off either the left end or the right end of the row. Return the most points you can score.

Write max_points(cards, k). Trying every split (i from the left, k - i from the right) is O(k^2) if each split is summed from scratch. The shortcut is the complement window: the n - k cards you leave behind are one contiguous block in the middle, so the score is total - (smallest sum of any window of size n - k). Slide that fixed window. Handle k == n (the window is empty, so the answer is the total) and raise ValueError unless 0 <= k <= n. Check it against the split brute force on seeded inputs, and print the bug where the window has size k instead of n - k.

Q43Grouping The OnesMedium

Given a list of 0s and 1s, one swap exchanges the values at any two positions. Return the minimum swaps needed to group all the 1s into one contiguous block.

Write min_swaps_group(data). If there are ones 1s, the final block is some window of size ones. The swaps needed for a window equal the number of 0s inside it, which is ones - (ones in the window). So slide a fixed window of size ones and keep the most 1s seen in any window. Handle ones == 0 (no swaps). Then write min_swaps_group_circular(data) for a circular list, where the block may wrap around the end: windows start at any s in range(n) and read data[(s + j) % n]. Check both against brute forces on seeded inputs, and print a list where the linear answer is larger than the circular one.

Q44Where Each Maximum SitsMedium

Return the index of the maximum of every window of size k, not its value. When a window holds equal maxima, the tie-break is stated: the rightmost index wins.

Write window_argmax(items, k) with the list-plus-head-index deque (collections.deque is DSA Topic 11): dq[head:] holds indices whose values decrease from front to back. The tie-break is why the back pop uses <=: an equal value that arrives later replaces the earlier one. Check it against an oracle that picks the rightmost maximum of each slice, on seeded inputs with many ties. Then write the variant that pops with <, show that it returns the same maximum values but different indices, and print one case beside the truth.

Q45Max Minus Min Per WindowHard

Return max - min for every window of size k (the range of the window). A running sum cannot do this, because neither maximum nor minimum can be undone by subtraction.

Write window_ranges(items, k) in O(n) with two list-plus-head-index deques (collections.deque is DSA Topic 11): one with decreasing values for the maximum, one with increasing values for the minimum. Both are indices into items, both expire their front when it leaves the window, and each keeps its own head. Check it against max(slice) - min(slice) on seeded inputs with ties, then time both on n = 4,000 and k = 1,000 using a best_of(fn, repeats=3) helper.

Q46Longest Calm StretchHard

A calm stretch is a subarray whose max - min <= limit. Return the length of the longest calm stretch. Raise ValueError for limit < 0, and return 0 for an empty list.

Write longest_calm(items, limit) as a variable window. It opens with the validity sentence, # INVALID when: max - min of the window > limit, and both list-plus-head-index deques (collections.deque is DSA Topic 11) decide it: the fronts are the window's maximum and minimum. When the window is invalid, advance left one step at a time and expire any front that has fallen off. Shrinking a valid window keeps it valid (the maximum can only fall, the minimum only rise), which is the monotonicity the template needs. Fuzz it against an O(n^2) brute force on seeded inputs, and test the edge cases limit == 0 and a list with one element.

Q47Repeated DNA SequencesEasy

A DNA string uses the letters A, C, G and T. Return every 10-letter sequence that occurs more than once, sorted, each reported once.

Write repeated_sequences(s, length=10) as a fixed window of strings: the window is s[left:left + length], and a seen set remembers every sequence met so far, while a repeated set collects the ones seen again. Return sorted(repeated). Check it against an O(n^2) brute force that compares every pair of starts, on seeded two-letter strings, and say in a comment what each window costs in time and memory (slicing copies length letters).

Q48Distinct And Length kMedium

Find the maximum sum of a window of size k whose elements are all distinct. If no window of size k has all-distinct elements, return None. Raise ValueError for k <= 0.

Write max_distinct_window_sum(items, k) that maintains both window_sum and a counts dict as the window slides, deleting a key when its count reaches 0 so len(counts) == k means "all distinct". Check it against a brute force on seeded inputs (including k > n), and show the bug where the code ignores distinctness and returns the plain largest window sum.

Q49Scoring Every WindowEasy

A dieter eats calories[i] on day i. Look at every window of k consecutive days and let T be its total calories. The window scores -1 if T < lower, +1 if T > upper, and 0 otherwise (a total equal to a bound is neutral). Return the sum of the scores over all windows. If k > len(calories) there are no windows and the answer is 0.

Write diet_score(calories, k, lower, upper) with a running window_sum. Check it against a brute force on seeded inputs, run the three published examples, and print the off-by-one bug where the comparisons use <= and >=.

Q50From Statement To WindowEasy

Choosing the right tool is half the work. Below are ten problem statements, each described by a few yes/no properties. Write classify(props) that maps the properties to one shape: fixed, longest-valid, shortest-valid, counting, exactly-by-subtraction, or not a window. For a not a window result it also returns the reason (non-contiguous, negatives, or non-monotone).

The rule for each shape must be written in code, in a sensible order: contiguity first, then negatives in sum conditions, then a stated size, then exactness, then monotonicity, then the goal. Run it on all ten statements, assert each result against the expected shape, and print a table sorted by shape. Then show that putting the goal check before the negatives check misclassifies a statement.

Q51Maximum Erasure ValueMedium

You may erase exactly one contiguous subarray of a list of positive integers, and you score the sum of what you erased. The catch is that the erased subarray must contain no repeated value. Return the best possible score. Write the validity sentence first, then a window that carries a running window_sum alongside its counts, and check it against an enumeration of every subarray.

Q52Counting "At Least" WindowsMediumMust Do

Given a string s made only of the letters a, b and c, count the substrings that contain at least one a, one b and one c. A substring is counted once per pair of start and end positions.

Once a window [left, right] is valid, every window that extends further to the right is valid too. Use that fact to count without looking at each window: either add left for every right, or add n - right for every left. Write both, say in a comment why each count is right, and check both against an enumeration of every substring.

Q53The Maximum Appears k TimesMedium

Given a list of integers items and a positive integer k, count the subarrays in which the global maximum of the whole list appears at least k times. Note that the maximum is fixed before the scan starts; it is not the maximum of each window. Raise ValueError when k <= 0.

Q54Removing From Both EndsMediumMust Do

You have a list of non-negative integers items and a target x. In one operation you remove either the leftmost or the rightmost element, and you want the removed values to add up to exactly x. Return the fewest operations, or -1 if it cannot be done.

Hint: what stays behind is one contiguous block in the middle. Turn the problem into "find the longest window whose sum is total - x", and answer n minus its length. Cover the -1 case, and the case where the target is 0 (everything must be removed, unless zeros sit in the middle). Verify against a brute force that tries every pair of prefix and suffix.

Q55Frequency After k IncrementsHardMust Do

You may add 1 to any element of a list of positive integers, at most k times in total (all increments together). Return the highest frequency any single value can have afterwards.

After sorting, the best group is a block of neighbours raised to its largest member. Keep a window whose cost items[right] * length - window_sum is at most k. Explain why sorting is what makes that condition monotone, and compare against the same code on unsorted input. Add a note about integer overflow in other languages. Verify against a brute force that does not use windows.

Q56Bits That Never OverlapMedium

Given a list of non-negative integers, find the length of the longest subarray in which every pair of elements has a bitwise AND of 0, meaning no two elements share a set bit. Keep one integer mask holding the OR of the window. Say the invalid sentence, add with OR, remove with XOR, and explain why XOR removal is exact here (and would not be for a general window).

Q57OR At Least kHard

Given a list of non-negative integers (each below 2^30) and a target k, find the length of the shortest non-empty subarray whose bitwise OR is at least k. Return -1 if none exists. Validity is monotone (a bigger window has an OR with a superset of the bits, so its OR is at least as large). But unlike the previous problem you cannot remove with XOR, because items overlap. Keep 30 per-bit counts. Show the mask-only version failing on a concrete input.

Q58Fixing A ParameterHardMust Do

Given a lowercase string s and an integer k >= 1, return the length of the longest substring in which every character that appears does so at least k times.

This validity is not monotone: adding a character can make a valid window invalid and a later character can make it valid again, so one window cannot decide. First show a single-window attempt giving a wrong answer. Then add a constraint that restores monotonicity: for each target t = 1..26, run a window that allows at most t distinct letters, and record only when exactly t distinct letters are present and all of them have a count of at least k. Verify against a brute force and count the work to show O(26 * n).

Q59Concatenation Of All WordsHard

Given a string s and a list words in which every word has the same length L (words may repeat), return the sorted list of start indices where s contains the concatenation of all the words, in any order, with nothing in between. Use L offsets: for each offset from 0 to L - 1, run a window over the words at positions offset, offset + L, ..., with a dict of counts. Verify against a brute force.

Q60Windows Over TimeMedium

Given a sorted list of event timestamps (in seconds, repeats allowed) and a span T, return the largest number of events in any half-open span [start, start + T); that is, the largest set of events whose times differ by less than T. The window here is defined by value (times[right] - times[left] < T), not by a fixed count. Write the validity sentence, check against an enumeration, and show what changes when the rule is <= T.

Q61Sliding Median With bisectHardMust Do

A median cannot be kept with a running add/subtract, because the middle item changes when the window moves. Keep the window's items sorted in a plain list: bisect.insort adds the entering item, and bisect_left finds the leaving item so you can del it. Write sliding_medians(items, k) returning, for every window of size k, the pair (lower_middle, upper_middle). For odd k the two are equal, so there are no float ambiguities. Check it against "sort every window" on seeded random inputs with plenty of duplicates, time both at n = 4,000 and k = 1,000, and say in a comment what O(n log k) needs (a heap, DSA Topic 15).

Q62Window Or Search On The AnswerMedium

Find the shortest length of a subarray with sum >= target (positive integers, target >= 1; return 0 if none exists) in two ways. First, binary search on the length (DSA Topic 3): a fixed-window check answers "does any window of length L reach the target?", and the answer is monotone in L for positive values. Second, the variable window, which finds the answer in one pass. Check that they agree on seeded inputs, time both at n = 100,000, and say when the search-on-the-answer version is the one to reach for.

Q63k Closest ValuesMedium

Given a sorted list arr, a count k and a value x, return the k values closest to x, in sorted order. Tie rule: when two values are equally close, the smaller value wins. Write two versions. (1) closest_window: start with the first k values as a window and slide it right while the incoming value is strictly closer to x than the leaving one. (2) closest_search: binary-search the window's start (DSA Topic 3), comparing the two ends of each candidate window. Check both against a brute force that sorts by (distance, value), and time them at n = 200,000.

Q64Two Non-Overlapping WindowsHard

Given items and two lengths a and b, return the maximum total of an a-window plus a b-window that do not overlap, or None if a + b > len(items). Items may be negative. Slide the b window to the right and keep, alongside it, the best a window that ended before it started. Then run it again with the roles swapped, because the a window may sit on either side. Check against a brute force over all start pairs, and show the single-order version failing.

Q65The Best k-by-k BlockHard

Find the maximum sum of any k x k block of a grid of integers (return None if the block does not fit). Slide a window down the rows, keeping a list col_sums of each column's sum over the last k rows, then slide a fixed window of k across col_sums. This is two sliding sums nested. Do not build a 2-D table of running totals: that is the prefix-sum technique of DSA Topic 6, and the answer should say so. Check against a brute force that adds every block cell by cell, and time both.

Q66Rolling FingerprintsHard

Rabin–Karp: slide a window of length L over a string and keep a rolling polynomial hash (multiply by a base and add the entering character, subtract the leaving character's term). Write first_repeat(s, L) returning (earlier, later), the start of the first window that duplicates an earlier one and the start of its first earlier copy, or None. Equal hashes are only a hint, so verify every hit by comparing the actual substrings. Use a tiny modulus to force collisions, show the verification catching them, show the unverified version returning a wrong answer, and note where C or Java would overflow.

Q67The Turbulent RunMedium

A subarray is turbulent when the comparisons between neighbours strictly alternate: up, down, up, … or down, up, down, …. Equal neighbours break the pattern. Return the length of the longest turbulent subarray (a single element counts as 1, an empty list gives 0). Write it as a window that does not shrink one step at a time but resets the moment the pattern breaks. Check against a brute force that tests every subarray, then show the tempting version that forgets equal neighbours printing a wrong answer.

Q68Fruits On A LineHard

Fruit trees stand at distinct integer positions on a line: fruits is a list of (position, amount) pairs sorted by position. You start at start and may walk at most k steps in total; every tree you pass is harvested. Return the maximum harvest. A harvested set of trees is a contiguous run fruits[left:right + 1], so it is a window over trees chosen by position. Let a be the steps you must go left of start and b the steps right of it (zero when the window is on one side). The cheapest walk is min(2*a + b, a + 2*b). Check against an oracle that tries every reachable interval of positions, and fuzz it.

Q69Sum In A Repeating ArrayMedium

The list items (positive integers) is repeated forever: items + items + items + .... Return the length of the shortest subarray of that infinite list whose sum equals target, or -1 if none exists. A target may be astronomically larger than the list, so you cannot build the repeated list. Take whole cycles first, then solve the remainder with a window over the list doubled once. Explain in a comment why whole cycles first is correct, check against a brute force that walks around the cycle, and show target = 10**12 finishing instantly.

Q70Choosing The TechniqueMedium

Eight problems, eight techniques. Describe each problem by a few properties (is it contiguous, is the input sorted, is the size fixed, are values non-negative, is the validity condition monotone, does it ask for a window maximum, a top-k, a pair in sorted order, a lookup in sorted order, a tiny n). Write route(props) that decides on those properties, in a stated order, and returns the technique with its topic. Compute the "monotone" property for two of the problems with a checker instead of asserting it, route all eight, and check the table.

Q71The Negative Number TrapHardMust Do

shortest_at_least below returns the length of the shortest subarray whose sum is at least k (or -1 if there is none). It uses the shortest-valid template and passes every test with non-negative values. Then a caller passes values that can be negative. Run it on [3, -2, 1, 4] with k = 5 and on [1, -5, 3, 3] with k = 6, print its answers beside the truth, and explain which assumption broke. Write the honest O(n^2) scan, fuzz both versions against it with random.Random(5), and report how often the template is wrong with and without negatives. Name the O(n) technique that handles negatives, but do not build it.

def shortest_at_least(items, k):
    best = -1
    window_sum = 0
    left = 0
    for right in range(len(items)):
        window_sum += items[right]
        while left <= right and window_sum >= k:
            if best == -1 or right - left + 1 < best:
                best = right - left + 1
            window_sum -= items[left]
            left += 1
    return best
Q72Zero Counts That LingerMedium

This "longest substring with at most k distinct characters" never crashes and often gives the right number. It is still wrong. Find the bug, then search (do not guess) for the smallest failing input over the alphabet "abc" and print it with the wrong answer and the truth. Explain why the left <= right guard turns a crash into a silent wrong answer. Fix the bug and fuzz the fix with random.Random(5).

def longest_k_distinct(s, k):
    counts = {}
    left = 0
    best = 0
    for right in range(len(s)):
        counts[s[right]] = counts.get(s[right], 0) + 1
        while left <= right and len(counts) > k:
            counts[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best
Q73Recording In The Wrong PlaceMedium

Two students wrote "minimum window of s containing every character of t" (with multiplicity, leftmost window on ties) by copying the longest-valid habit of recording after the shrink loop. Student A records only if missing == 0. Student B records s[left:right + 1] whenever the loop shrank anything. Run both on s = "ADOBECODEBANC", t = "ABC". Student B's answer is wrong in a very specific way: find out exactly how it relates to the true answer, and prove it with a fuzz using random.Random(5). Explain why A can never record anything. Then state the rule for where a shortest-valid window records, fix it and fuzz the fix.

Q74if Where while BelongsHard

Shortest subarray with sum at least target, non-negative values. One version shrinks with while window_sum >= target, another with if. Show the if version giving a wrong answer on [1, 1, 1, 10] with target = 10. Then explain exactly what it computes instead, prove it, and pin down the input shape that triggers the bug: one step that makes the window removable by more than one element. Check both claims with a fuzz against a brute force, using random.Random(5).

Q75The Window That Never ShrinksHardMust Do

For a longest-valid problem, replacing the shrink while with an if is a known, deliberate trick. Take "longest subarray with sum <= k" (non-negative values). Write the if version, which returns the final window size len(items) - left, and prove it equals the answer. Connect the proof to the longest-repeating-replacement solution, whose max_count is never decreased. Then show where the trick breaks: when you need the window itself, and when you need a property other than its length (the number of valid windows). Fuzz all three claims with random.Random(5).

Q76Off By One In The LengthMedium

Two conventions for a window exist: closed [left, right] with length right - left + 1, and half-open [left, right) with length right - left. Mixing them gives an off-by-one. Write the correct "longest subarray with sum <= k" in both conventions, plus the two classic slips: closed bounds with right - left, and half-open bounds with right - left + 1. Fuzz all four against a brute force with random.Random(5), print the smallest failing input for each slip, and print the convention this topic uses.

Q77The Stale Maximum BitesHard

In "longest substring that can be made one letter with at most k replacements" (lowercase letters), a max_count that is never decreased still gives the right length. Now the caller wants more: the window's bounds and the letter it turns into. Tie-breaks: the rightmost longest window, and the alphabetically smallest of its most frequent letters. Show that the stale-max_count version returns invalid bounds or a wrong letter while its length stays right, find a short failing input with random.Random(5), and fix it.

Q78Not Every Condition Is MonotoneHard

"Longest substring in which every letter appears an even number of times." The template looks natural: # INVALID when: some letter has an odd count. Write it, run it on "abab" and "xaayy", and print its answers beside a brute force. Explain why the template cannot work here, show the monotone-condition property failing on a concrete window, fuzz how often the template is wrong with random.Random(5), and name the O(n) technique without building it.

Q79Equal Is Not LessHard

Two counting problems, two easy slips. (1) Count subarrays with product strictly less than k (positive integers); the slip shrinks while product > k. (2) Count subarrays with sum at most k (non-negative integers); the slip shrinks while window_sum >= k. Fuzz each slip against a brute force with random.Random(5) and sort the disagreements into edge cases: k = 0, k = 1, and "some window equals k exactly". Print which edge cases make the slips differ and which never do.

Q80The Empty WindowMedium

Longest subarray with sum <= k, non-negative items. The template is correct for every k >= 0, because the empty window (sum 0) is always valid, so the shrink loop stops on its own. A caller passes k = -1. Now even the empty window is invalid. Trace the unguarded version below on [2, 7, 1] with k = -1, and print the sums and the window bounds it reaches before it fails. Then fuzz it with random.Random(5) to find out how often it fails. Write two fixes, a left <= right guard and an early if k < 0: return 0, fuzz both against a brute force, and say which one you would ship.

def longest_at_most(items, k):
    window_sum = 0
    left = 0
    best = 0
    for right in range(len(items)):
        window_sum += items[right]
        while window_sum > k:
            window_sum -= items[left]
            left += 1
        best = max(best, right - left + 1)
    return best
Q81Drift In A Running AverageHard

A moving average over a fixed window is kept as a running window_sum: add the entering value, subtract the leaving one. With floats, every add and subtract rounds, and the rounding errors never cancel exactly. Over 10^6 seeded updates (window k = 1,000, mostly small values and the occasional huge one), measure the drift between the running sum and the recomputed math.fsum of the window at checkpoints. Then show the fixes and print the drift of each: integers (scale to whole units), a periodic recompute, and math.fsum itself.

Q82Changing The Input Mid-ScanMedium

A window solver for "longest run of 1s if at most k zeros may be flipped" is tempted to actually flip the zeros inside the input list as it scans. Write that version, then show two things: it returns a wrong answer, and it leaves the caller's list changed. Then write the version that keeps the window's state (zeros) separate and never touches the input, and check that the input is unchanged.

Q83The O(n) That Is NotMedium

A loop that looks like a sliding window can still be quadratic if the validity test recomputes the window: sum(items[left:right + 1]) or len(set(window)) inside the while costs O(window) every time it is evaluated. Write both slow versions next to the running-state versions, check they agree, and measure the time as the window gets wider and as n doubles. Draw the conclusion from the printed numbers.

Q84The 26-Slot AssumptionMedium

An anagram finder keeps its counts in a 26-slot list indexed by ord(ch) - ord("a"). That quietly assumes the text is lowercase a–z. Feed it uppercase letters, digits, or a non-ASCII character (build it with chr(), and print every string with ascii()) and see what happens: some inputs raise IndexError, and some silently count as a different letter. Then show two repairs: validate the input, or use a dict. Fuzz the dict version on a hostile alphabet.

Q85The Suite That Catches All Of ItHardMust Do

Write one differential harness: it runs a solver against a brute-force _truth on every small input (empty input, zeros, and every k edge included), and returns the smallest input that disagrees, or None. Use it on the correct window solvers and on a set of deliberately buggy versions, one for each mistake common in this band: wrong comparison, off-by-one length, recording in the wrong place, stale zero counts, if instead of while, a bad starting value, and the negatives trap. Print a catch table naming each bug, whether it was caught, and the smallest failing input with what the bug returned beside the truth.

Q86The Window TracerMini-ProjectMust Do

Build trace_window(items, add, remove, invalid, describe): a longest-valid sliding window that prints every step. For each right it shows the entering element, each shrink step, the window as ASCII under the items, the state (via describe), and the best so far. It must return (best_length, best_left) with ties going to the earliest window, so it can be fuzzed against brute force. Demo it on three different problems by passing different add, remove and invalid callbacks.

Q87A Shrinker For Window BugsMini-Project

DSA Topic 4 built a generic differential fuzzer; this question reuses that idea and spends its effort on the shrinker, tuned to where window code actually breaks: the value of k (down to 0 and 1), the stream length, the boundary items at either end, and values toward 0. Build fuzz(solver, oracle, gen, rng, trials) (a crash counts as a failure) and shrink(case, fails) whose every accepted step strictly reduces a stated measure, so it cannot loop forever. Use it on two seeded buggy solvers of "longest subarray with sum <= k", print the original and the shrunk failing input, show which kinds of shrink step were accepted, and check the result is 1-minimal. Run it on the correct solver to show it reports no bug, and repeat on several seeds to show the tool does not depend on one lucky seed.

Q88A Sliding-Log Rate LimiterMini-Project

Build RateLimiter(limit, period): allow at most limit requests per period seconds per user, deciding each request in the order it arrives. A request at time now is allowed if fewer than limit allowed requests by the same user happened in (now - period, now]. Keep each user's log as a plain list plus a head index (the collections.deque is DSA Topic 11), evicting from the front as time passes, and compact the dead prefix so memory stays small. Include a demo on a fixed log with a decisions table and a per-user summary, a fuzz against a brute-force limiter_truth, and a timing.

Q89The Log Window AnalyzerMini-Project

Build a small analyzer for a seeded event log of (timestamp, user) pairs, sorted by time. Report, for a period in seconds: (1) the busiest window, the most events in any span shorter than period; (2) the most distinct users in any such window; (3) the longest quiet gap between consecutive events. The windows are defined by time, not by count. Print a report table for three periods, fuzz each metric against a brute-force _truth, and time one of them.

Q90The Anagram Search ServiceMini-Project

Build AnagramIndex(text): index a lowercase text once, then answer "where do anagrams of this pattern start?" queries. Offer scan(pattern), which uses the match counter (O(1) per step, no 26-slot comparison), and query(pattern), which caches, per pattern length, a table from each window's letter counts to its start indices, so later queries of that length are lookups. Validate the input. Fuzz all three methods against brute force, and benchmark brute force, scan and the cached index on a batch of queries.

Q91The Plagiarism CheckerMini-Project

Build a plagiarism checker for two texts. Split each text into words and slide a fixed window of k words (a k-shingle) across it. Give every shingle a rolling fingerprint: when the window moves one word, update the fingerprint in O(1) by taking out the leaving word and adding the entering one, instead of rehashing all k words. Then:

  1. Report the Jaccard similarity of the two shingle sets, |A & B| / |A | B|.
  2. Find every pair of matching shingles. Verify each match word by word, because equal fingerprints only mean "probably equal".
  3. Merge runs of consecutive matches into shared passages and print them.

Check it against a brute-force plagiarism_truth that compares word tuples, on 500 random cases with random.Random(5). Show what verification saves you from by rerunning the demo with a tiny modulus. Finally, time the checker against the all-pairs brute force.

Q92The Price Window DashboardMini-Project

Build a dashboard over a price series (integer cents, a seeded random walk). For every window of the last k prices, report the moving maximum, the moving minimum and the integer moving average window_sum // k, all in one O(n) pass. The max and min come from two monotonic deques, each written as a plain list plus a head index.

Then add breakout detection: a price is an up breakout when it is above every one of the previous k prices, and a down breakout when it is below all of them. Draw an ASCII chart that shows the price, the max–min band, and the breakout marks. Fuzz everything against dashboard_truth with random.Random(5), and time the dashboard against recomputing each window.

Q93The Template EngineMini-ProjectMust Do

Every variable window in this topic is the same loop with a different condition. Build the loop once, as three engines that take callbacks for the problem-specific parts:

  • longest_valid(items, make_state, add, remove, invalid) returns the length and start of the longest valid window (leftmost on ties).
  • shortest_valid(...) returns the shortest valid window (leftmost on ties), or length 0 if there is none.
  • count_valid(...) returns how many non-empty windows are valid.

Then plug in four problems, each written as its make_state, add, remove and invalid callbacks plus its one-sentence invalid condition: longest substring without repeats, longest substring with at most 2 distinct characters, shortest subarray with sum at least a target (non-negative values), and the count of subarrays with product below a limit (positive values). Check every problem against a brute force that enumerates every window, and show that remove is called at most n times.

Q94The DNA Motif ScannerMini-Project

Build a scanner for a seeded random genome over ACGT, with a GC-rich island and a repeated motif planted in it. It uses fixed windows only:

  1. GC content of every window of w bases, with a running count. Report the window with the highest GC count (the leftmost on ties) and the regions where GC is at least 65%.
  2. The most frequent k-mers (substrings of length k), with ties broken by the k-mer itself in alphabetical order. Roll each k-mer as a 2-bits-per-base integer code: shift left two bits, OR in the entering base, and mask off the leaving one.
  3. Every repeated sequence: each k-mer that occurs more than once, sorted.

Fuzz all three against brute-force *_truth functions that slice every window, using random.Random(5).

Q95The Crossover BenchmarkMini-Project

Take one problem, the shortest subarray with sum at least target over non-negative values, and solve it three ways:

  • brute: from each left, add rightwards until the sum reaches the target, then stop. O(n^2).
  • binary search on the length: a length L is feasible when some window of size L reaches the target, and feasibility is monotone in L because values are non-negative. Test each length with a fixed sliding sum. O(n log n).
  • the window: the shortest-valid loop. O(n).

Fuzz all three against each other with random.Random(5). Then time them across doubling n (min of 3 runs, many small instances per size so that small n can be measured). Print a table, find the crossover point where brute force stops winning, and draw the conclusion from the numbers you printed.

Q96Explaining It ColdInterview

An interviewer says: "Explain the sliding window to me as if I had never seen it. Then solve two problems with it while I watch." Write the answer as code plus a printed script. The script should cover the five lines of the template, the one sentence that defines "invalid", and why the loop is O(n) even though it has a while inside a for. The two problems are the longest substring without repeating characters and the shortest subarray with sum at least a target. Trace each one on a small input, check each against a brute force, and measure the movement budget on a large input.

Q97Diagnosing By ReasoningInterview

You are handed five window solutions, and each one has one bug. For each, write down the failing input and the wrong output you predict before running anything, with the reasoning that led you there. Then run each one to confirm the prediction, show the fix, and fuzz the fixed version. The five are: a fixed-window maximum sum, the longest substring with at most k distinct characters, the shortest subarray with sum at least a target, the sliding-window maximum with a list deque, and the longest subarray with sum at most a limit.

Q98Designing For QueriesInterview

"Here is one string of lowercase letters and many queries. Each query gives k and asks for the length of the longest substring with at most k distinct characters. Design it." Compare three strategies:

  • per query: run the window for every query, O(q * n).
  • precompute: run the window once for each k from 1 to D, the number of distinct letters, then answer every query by lookup. That is O(n * D) once, then O(1) per query.
  • cache: run the window the first time a k is asked and remember the result.

Verify the window against a brute force. Then measure all three for several values of q, and say how you would choose based on q, on D, and on the numbers.

Q99The Mock InterviewInterview

Mock interview: minimum window substring. Given strings s and t, return the shortest substring of s that contains every character of t, counting repeats (the leftmost one if there is a tie, "" if there is none). Ask the clarifying questions, give the brute force, then the window, with its invalid sentence and a proof that the window finds the answer. State the complexity and the edge cases. Then handle three follow-ups:

  1. Return all minimal windows, and prove the loop visits every one of them.
  2. Characters of s arrive as a stream. Report the best window so far as stream positions, keep as little of s in memory as you can, and state the worst case.
  3. What changes for Unicode text?
Q100CapstoneInterviewMust Do

The capstone: build a window solver. A problem arrives as a spec: a one-sentence invalid condition, make_state, add, remove and invalid callbacks, a mode (longest, shortest, count or fixed with a size k), a claim of whether the condition is monotone, a flag for whether it needs non-negative inputs, and a generator of sample inputs. The solver must:

  1. Print the invalid sentence.
  2. Check the monotonicity claim on sample inputs by brute force. Refuse the spec if the claim is false or was never made, and point to the right tool.
  3. Pick the engine for the mode, and count how far left moves to show the movement budget.
  4. Verify the engine against a brute force by fuzzing.
  5. Refuse an input containing negatives when the spec needs non-negative values, and print the spec's own pointer to the tool that handles negatives for that problem (each problem needs a different one).

Demo it on six specs that cover fixed and variable windows, at least one false monotonicity claim, and at least one spec that is not monotone at all.

Stuck? Solve it with a mentor.

Your first 1-on-1 session is free.

Book my free session