Prefix Sums & Difference Arrays: 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.
An array items of n = 2,000 numbers gets q queries, each asking for the sum of items[left..right] (both ends inclusive). The obvious answer adds the items one by one for every query. Write answer_all_naive(items, queries) that returns the answers and the number of additions it performed. For q = 100, 400, 1,600 (random ranges from random.Random(6)), print the additions and the time using best_of(fn, repeats=3). Then say what happens to the cost when q grows by 4x.
A prefix array stores running totals: prefix[i] is the sum of the first i items, items[0:i]. It has n + 1 entries and prefix[0] = 0 (the sum of nothing). Write build_prefix(items) with a single loop using prefix.append(prefix[-1] + x). Print items and prefix aligned under an index row for [3, -1, 4, 1, -5, 9, 2, 6], and assert prefix[i] == sum(items[:i]) for every i, including on an empty list.
Since prefix[i] is the sum of items[0:i], the inclusive range items[left..right] is a difference of two prefixes: prefix[right + 1] - prefix[left]. Write range_sum(prefix, left, right). Check it against a brute force on 500 random arrays with every possible (left, right), then time 2,000 seeded queries on n = 4,000 for both approaches with best_of(fn, repeats=3) (min of 3 runs), building the prefix inside the timed prefix run.
Suppose you build a prefix array with only n entries, where short[i] is the sum of items[0..i] (no leading zero). A range starting at left == 0 then needs a special case, because short[left - 1] would read short[-1]. Write that version with its if, then a version that forgets the if. Show the forgotten-if version giving a wrong answer on a tiny input, count how many random queries it gets wrong, and explain why the n + 1 layout cannot have this bug.
There are two ways to name a range. Inclusive [left, right] includes both ends (this track's default). Half-open [start, stop) includes start but not stop, exactly like a Python slice. With prefix of length n + 1, the half-open form is prefix[stop] - prefix[start]. Write both, the translation stop = right + 1, and show that handing an inclusive right to the half-open function silently drops the last item. Count how often that happens over seeded queries, and show one advantage of half-open (an empty range).
Building a prefix array costs O(n) up front; each query then costs O(1), against O(n) per query without it. So for a handful of queries the simple loop can win. On n = 4,000, measure (min of 3 runs with best_of(fn, repeats=3)) the build time and the per-query cost of each approach, compute the break-even number of queries from those measurements, and print a table of total time at several q that shows which side wins each row.
Prefix sums count things too. Turn a property into a 0/1 indicator (1 if the item has it, 0 if not) and take the prefix of the indicators: the range sum is then "how many items in [left, right] have the property". Write build_count_prefix(items, has_property) and use it to count even numbers (negatives included) in a range, then reuse the same function to count vowels in a string. Check both against brute force.
To answer "how many times does letter c appear in s[left..right]" for any of the 26 lowercase letters, keep one prefix array per letter: table[c][i] is the count of letter c in s[0:i]. Build the table, answer queries in O(1), and check against s[left:right + 1].count(ch). Then measure the memory with sys.getsizeof for n = 1,000, 4,000, 16,000 and compare with the string's own size. Say what getsizeof does not count.
A ledger is a list of transactions: positive for deposits, negative for withdrawals. After transaction k the balance is opening + prefix[k + 1]. Write balances(transactions, opening) from a prefix array, and first_overdraft(transactions, opening) that returns the index of the first transaction after which the balance is below zero, or None. Print a small ledger as a table, and fuzz both against a direct simulation that keeps one running balance.
What is the smallest opening balance that keeps a ledger from ever going below zero? The balance at step k is opening + prefix[k + 1], so the account survives exactly when opening + min(prefix) >= 0. Because prefix[0] = 0 is part of the array, min(prefix) <= 0 always, and the answer is max(0, -min(prefix)). Write min_opening(transactions), and check it against a brute force that tries openings 0, 1, 2, ... and simulates each. Print one ledger with the lowest point marked.
A pivot index is an index i where the sum of everything strictly to its left equals the sum of everything strictly to its right. The item at i itself belongs to neither side. An empty side counts as 0, so index 0 is a pivot when the rest of the list sums to 0. Values may be negative.
Write pivot_indices(items) that returns every pivot, and pivot_index(items) that returns the leftmost one or -1. Build prefix once (n + 1 entries, prefix[0] = 0), then for each i read the left sum as prefix[i] and the right sum as total - prefix[i + 1]. Check it against a brute force on seeded random lists, including empty and one-item lists.
You have been building prefix with prefix.append(prefix[-1] + x). The standard library has the same thing: itertools.accumulate(items, initial=0) yields 0, then each running total. First write the hand loop build_prefix, and show that list(accumulate(items, initial=0)) gives the identical list on seeded random input. Show what accumulate(items) gives without initial (no leading zero, so only n entries). Then time both on 200,000 items with a best_of(fn, repeats=3) helper, and say when you would still write the loop.
prefix[i] is the sum of the first i items. The mirror image is suffix[i], the sum of items[i:], with n + 1 entries and suffix[n] = 0. Write build_suffix with one loop that runs from the right. Then show that suffix[i] == total - prefix[i], so a suffix can always be read off a prefix. A project has hours [3, 5, 2, 6, 4] (the hours needed per task, in order): print the hours still remaining after finishing each task, which is the sum strictly to the right, suffix[i + 1]. Finally recover range_sum(left, right) from the suffix alone, as suffix[left] - suffix[right + 1].
For a list items, return a list out where out[i] is the product of every item except items[i]. The tempting solution is total // items[i]. Show that it fails: with one zero in the list it divides by zero (and a guard that writes 0 there gives a wrong answer at the zero's own position), and with two zeros it crashes too. Then solve it with no division: pre[i] is the product of items[:i] and suf[i] is the product of items[i:], both with n + 1 entries starting from 1, and out[i] = pre[i] * suf[i + 1]. Check it against a brute force on seeded lists that contain zeros and negatives. State which operation has an inverse and which values break it.
Build px where px[i] is the XOR of items[:i] (n + 1 entries, px[0] = 0). Show that xor(left..right) = px[right + 1] ^ px[left], and explain in a comment why it works: x ^ x = 0, so XOR is its own inverse, and the shared prefix cancels. Check it against a brute force on seeded random queries, and print one worked example with the bits.
A prefix array answers a range by cancelling the shared part, and that needs an operation with an inverse. + has one (subtract) and ^ has one (itself). max, min and gcd do not: knowing the maximum of the first 9 items says nothing about the maximum of items 4 to 8. Build prefix arrays for sum, XOR, max, min and gcd of the same list, then try the "same trick" on every (left, right) pair and count how many answers are wrong for each operation. For max, min and gcd the best a prefix can offer is the value from the start, prefix[right + 1]; show that it is right exactly when left == 0.
When every value is non-negative, prefix never decreases, so it is a sorted list and bisect (Topic 3) can search it. Using prefix (n + 1 entries, prefix[0] = 0), write first_reaching(prefix, x): the smallest number of leading items whose sum is at least x (or None if the whole list is too small), and most_within(prefix, budget): the largest number of leading items whose sum is at most budget (or None if even zero items exceed it, i.e. budget < 0). Check both against a linear scan on seeded input. Then show what happens with negative values, where prefix is no longer sorted and bisect quietly returns a wrong answer.
Pick an index with probability proportional to its weight. Build prefix of the weights (n + 1 entries). Draw r = rng.randrange(total) with a seeded random.Random(6). Index i owns the half-open slice [prefix[i], prefix[i + 1]) of 0..total-1, so the pick is bisect_right(prefix, r) - 1. Draw 60,000 times with weights [5, 0, 3, 1, 0, 11] and print the expected and observed share per index (a weight of 0 must never be picked). Then show that using bisect_left instead gives a wrong mapping from r to index, even though the overall shares can still look right, so a frequency check alone is not enough. Finally time the bisect pick against a linear walk that subtracts weights one by one.
A prefix array makes reads cheap. The mirror problem is writes: add v to every item in [left, right], u times, then read the final array. Naively that is a loop over the range per update. Instead keep diff with n + 1 entries and record each update as two writes: diff[left] += v (the extra starts here) and diff[right + 1] -= v (it stops after right). When all updates are in, rebuild the array with a running sum over the first n entries of diff. Print diff and the result for a small example, check against the naive version on seeded random updates, and time both on n = 5,000 with 1,500 updates using a best_of(fn, repeats=3) helper.
The difference array only wins when updates are batched before the read. Using n = 4,000 and u of 100, 200, 400, 800 random range-adds, count the elementary writes done by the naive loop (every item touched) and by the difference array (2 * u writes plus an n-step rebuild), and time both with a best_of(fn, repeats=3) helper. Then show the catch: if you must read the whole array after every single update, the difference array has to rebuild each time, and the advantage disappears. Print the table, and draw the conclusion from the same numbers.
A prefix array is a running sum and a difference array is a pairwise subtraction, so each should undo the other. Write build_prefix(items) (n + 1 entries, leading zero) and difference(items) (n + 1 entries: diff[0] = items[0], diff[i] = items[i] - items[i - 1], and a closing diff[n] = -items[n - 1], the slot a range add writes to). Show both directions on one array and by fuzz: (1) the pairwise differences of prefix give items back, and (2) the running sum of the first n entries of difference(items) gives items back. Print one example, then fuzz 500 seeded arrays.
For a grid with rows rows and cols columns, the 2-D prefix table P has rows + 1 rows and cols + 1 columns, a zero first row and a zero first column, and P[r][c] is the sum of the block grid[0:r][0:c]. Build it with P[r + 1][c + 1] = grid[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c]. Print a seeded 4 x 5 grid beside its table, then check every P[r][c] against a direct double loop on 300 seeded grids (including 1 x 1 and 1 x n shapes). State why P[r][c] must be subtracted once.
Given the 2-D prefix table P (zero first row and column), the sum of the rectangle with top-left (r1, c1) and bottom-right (r2, c2) (both inclusive) is P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1]. Write rect_sum(P, r1, c1, r2, c2). Draw a picture that shows why the last term is added back: print a small grid in which each cell is marked # (inside the rectangle), u (removed by the strip above), l (removed by the strip on the left), x (removed twice, so added back) or . (never counted). Then fuzz rect_sum against a brute-force loop on 400 seeded grids with every rectangle of each.
Sliding Window (Topic 5) left one case broken: the longest subarray with sum <= k when the items can be negative, because shrinking the window no longer lowers the sum. Re-create that window function longest_sum_at_most_window(items, k) and an honest prefix-based longest_sum_at_most(items, k): for every right, scan left from the smallest value and take the first with prefix[right + 1] - prefix[left] <= k. Finally write longest_at_most_fast(items, k) in O(n log n): take the running maximum of prefix and binary-search it with bisect. Print the first short input (values -2..2, searched smallest first) where the window is wrong and the prefix scan is right, then fuzz 2,000 seeded inputs with negatives and print how often each is wrong. Prefix sums subtract, and subtraction does not care about the sign of an item. As the last step, fuzz longest_at_most_fast against the O(n^2) prefix scan on 2,000 seeded inputs with negatives, counting any exception as a failure.
Route ten statements to sliding window, prefix sums, both work, or neither. Each statement has three yes/no properties: is the operation invertible (a range answer can be recovered by subtraction), is the condition monotone (growing the window never rescues an invalid one, shrinking never breaks a valid one), and is it a single scan (one answer for the whole array, not many independent queries). Encode the rule in route(invertible, monotone, single_scan) and print a ten-row table. Then back two of the "both" rows with code: they must agree on 1,000 seeded inputs.
Count the non-empty contiguous subarrays of items whose sum equals k. Items may be negative, so the sliding window does not apply. Write count_naive(items, k): build prefix (n + 1 entries), then try every pair left < right + 1 and test prefix[right + 1] - prefix[left] == k. Return the count and the number of pairs tested. Print the answer and the pair count for [1, 2, 3, -3, 3] and k = 3, list the subarrays found, then print pairs tested and the best-of-3 time for n = 500, 1,000, 2,000 to show the quadratic growth.
A subarray ending at right has sum k exactly when some earlier prefix equals prefix_now - k. Keep seen, a dict from prefix value to how many times it has occurred. Walk items once with a running total; at each step first add seen.get(total - k, 0) to the count, and only then record total in seen. Write count_subarrays(items, k) (negatives allowed), fuzz it against the naive pair-testing version on 1,000 seeded inputs, and time both for n = 2,000 with best_of(fn, repeats=3). Hash tables themselves are DSA Topic 7; here a dict is just a counter.
The dict of prefixes starts as {0: 1}, not {}. Show why. Write count_no_seed(items, k) (starts with an empty dict) and count_seeded(items, k) (starts with {0: 1}), both querying before inserting. Find the smallest input where they disagree and print both counts beside a brute-force truth. Then fuzz 2,000 seeded inputs and print how often the unseeded version is wrong. Finish by explaining in a comment what the seed stands for: prefix[0] = 0, the empty prefix that sits before index 0.
Over one list items and one target k, answer three different questions with the prefix idea: (1) how many subarrays sum to k, (2) the longest one, (3) the shortest non-empty one. Each needs a different dict. Counting stores how many times each prefix occurred, seeded {0: 1}. Longest stores the first index of each prefix and never overwrites, seeded {0: -1}. Shortest stores the latest index and overwrites every time, seeded {0: -1}. Query before inserting in all three. Write them, print the three answers on [1, -1, 5, -2, 3, 2, -2, 4] with k = 3, and fuzz all three against brute force on 1,000 seeded inputs.
Write longest_sum_k(items, k) using first = {0: -1}, a dict from prefix value to the first index where it occurred, and returning the length of the longest subarray with sum k (0 if none). Then write longest_overwrite(items, k), which updates first[total] = right on every step. Search short lists over -2..2 for the smallest input where the overwrite version is too short and print both answers beside the truth. Then fuzz 2,000 seeded inputs and print how often each version is wrong.
A list bits holds only 0s and 1s. Find the length of the longest subarray with equally many 0s and 1s. Map each 0 to -1 (and each 1 to +1), and the question becomes "longest subarray with sum 0", which the first-occurrence map answers in one pass. Write longest_balanced_truth (brute force) and longest_balanced, and fuzz them on 2,000 seeded inputs. Then break it two ways and print the wrong answers: (a) skip the mapping, so 0 stays 0, and (b) start the map empty instead of {0: -1}. Say in a comment which seed form this uses and why.
Count the subarrays of items whose sum is divisible by k (a positive integer). Two prefixes prefix[i] and prefix[j] give a divisible subarray items[i..j-1] exactly when they leave the same remainder mod k, so keep a dict that counts how many prefixes had each remainder. Write count_divisible_truth (brute force) and count_divisible, and check them on the example [4, 5, 0, -2, -3, 1] with k = 5 and on 2,000 seeded inputs with negatives. Then write count_divisible_c_style, which takes remainders the way C and Java do (the sign follows the dividend, emulated with math.fmod), and print where it goes wrong. Comment which seed form you use and why, and say what Python's % does with negatives.
Return True if some subarray of length at least 2 has a sum that is a multiple of k. Use a map from prefix % k to the first index where it appeared, so a match at least two positions later is a long-enough subarray. Handle k = 0 explicitly: the only multiple of 0 is 0, so the sum itself must be 0 (state this in a comment). Write the brute force has_multiple_truth, then has_multiple, and fuzz them on 2,000 seeded inputs including k = 0. Show that overwriting the first index with the latest one gives wrong answers, and print the smallest failing input.
Count the subarrays of non-negative integers whose XOR is exactly k. The prefix XOR px works like a prefix sum, except that XOR is its own inverse: xor(left..right) = px[right + 1] ^ px[left], so the partner you need is px ^ k. Write count_xor_truth (brute force), count_xor (one pass with a dict), and a broken count_xor_minus that looks up px - k out of habit from sum problems. Fuzz all three on 2,000 seeded inputs and print the worked example. Comment which seed form you use and why.
An array items of 4,000 integers gets 2,000 queries (left, right) (inclusive), each asking for the XOR of items[left..right]. Build px once, with px[0] = 0 and px[i + 1] = px[i] ^ items[i], and answer each query as px[right + 1] ^ px[left]. Compare against a naive loop that XORs each range item by item, time both with best_of(fn, repeats=3), and print the ratio. Also show that the off-by-one px[right] ^ px[left] gives wrong answers.
There are n flights numbered 1..n. Each booking is (first, last, seats): it reserves seats seats on every flight from first to last, both inclusive. Return the total seats booked on each flight. Doing seats additions per flight per booking is O(bookings * n). Instead, write flight_totals(n, bookings) with a difference array: add at the start, subtract just past the end, rebuild with one running sum. Fuzz it against a naive version on 2,000 seeded inputs. Then show the bug when diff has only n entries and a booking ends on flight n.
A car with capacity seats drives past stops 0..1000 in order. Each trip is (passengers, pickup, dropoff): the passengers get in at pickup and get out at dropoff, so they occupy seats on stops pickup .. dropoff - 1, and a seat freed at dropoff can be taken at the same stop. Write car_pooling(trips, capacity) that returns (ok, first_bad_stop) using a difference array over the stop numbers (no sorting of events; the sweep over sorted events is a Topic 9 technique). Check it against a stop-by-stop simulation on 2,000 seeded inputs. Then show that treating dropoff as still occupied turns a valid hand-over into a false "overloaded".
A list items receives u range-add updates (left, right, value) (inclusive), all before any query. Afterwards q queries ask for sum(items[left..right]). Build two layers: a difference array applies every update in O(1), a running sum rebuilds the updated list, and a prefix array over that answers each query in O(1). Write apply_then_query(items, updates, queries) and a naive version that applies each update directly and sums each query. Fuzz them on 2,000 seeded inputs, then time both with best_of(fn, repeats=3) at n = 3,000, u = q = 1,500 and print the numbers.
An R x C grid starts at all zeros and receives updates (r1, c1, r2, c2, v): add v to every cell in the inclusive rectangle. Use a 2-D difference array D of size (R + 1) x (C + 1) with four corner writes per update, then rebuild the grid with a 2-D running sum: G[r][c] = D[r][c] + G[r-1][c] + G[r][c-1] - G[r-1][c-1]. Write apply_rectangles(R, C, updates) and a naive version, print a small example with its D and result, and fuzz 2,000 seeded cases. Show the grid you get when the fourth corner write D[r2+1][c2+1] += v is forgotten.
Given a grid and a radius k, return a grid answer where answer[r][c] is the sum of every cell (i, j) with r - k <= i <= r + k and c - k <= j <= c + k that lies inside the grid (windows are clamped at the borders). Doing this cell by cell costs O(R * C * k^2). Build a 2-D prefix table P of size (R + 1) x (C + 1) and answer each cell from four corners. Write block_sum_naive, block_sum, and block_sum_unclamped (which forgets to clamp and so reads outside the table), and fuzz them on 2,000 seeded grids, including negative values. Then time naive and prefix with best_of(fn, repeats=3) on a 50 x 50 grid for k = 2, 6, 12 and print the table.
A grid holds only 0 and 1. For every size k, count the k x k squares made entirely of ones. Testing a square cell by cell costs k^2. Build a 2-D prefix table P of size (R + 1) x (C + 1) instead: a square is all ones exactly when its sum is k * k, and the sum is four corner reads. Write count_squares_truth (checks every cell), count_squares (prefix table) and count_squares_edge_bug, which loops over range(R - k) and range(C - k) instead of R - k + 1 and C - k + 1. Return a list counts where counts[k] is the count for size k (index 0 unused). Check the three on a 3 x 3 grid of ones and on 2,000 seeded grids, and print how often the edge bug is wrong.
Find the largest sum of any rectangle in a grid (values may be negative) that does not exceed k, or None if every rectangle's sum is above k. Fix a pair of rows top <= bottom, add the rows into a 1-D array col of column sums, and then the question is 1-D: over prefixes cur of col, find the smallest earlier prefix that is at least cur - k, because cur - that_prefix is then the largest sum <= k ending here. Keep earlier prefixes in a sorted list and find that one with bisect_left, then add the new prefix with bisect.insort. Write best_rect_truth (every rectangle, from a 2-D prefix), best_rect, and best_rect_ignores_k, which takes the smallest earlier prefix instead and so returns the largest sum overall. State the honest cost: insort shifts list entries, so it is linear, not logarithmic. Fuzz on 400 seeded grids.
A list words holds lowercase words. A word is a vowel word if it both starts and ends with a vowel (a e i o u). Answer many queries (left, right), inclusive, with the number of vowel words in words[left..right]. Build a prefix array of the 0/1 indicator "is a vowel word", with n + 1 entries. Write count_truth, count_vowel_words and count_right_exclusive, which builds the correct prefix but treats right as exclusive (reads prefix[right] - prefix[left]), and show where it goes wrong. Check the example ["aba", "bcb", "ece", "aa", "e"] and 2,000 seeded inputs.
A lowercase string s is changed by a list of shifts, each (left, right, direction): every letter in s[left..right] (inclusive) moves one step forward in the alphabet if direction is 1, or one step back if it is 0, wrapping z to a and a to z. Applying each shift letter by letter costs O(n) per shift. Record each shift in a difference array diff with n + 1 entries (+1 or -1), rebuild the net shift of each position with a running sum, and apply it with % 26. Write shift_truth, shift_letters and shift_letters_short, which writes the closing - at diff[right] instead of diff[right + 1]. Check the example "abc" with [(0, 1, 0), (1, 2, 1), (0, 2, 1)] and 2,000 seeded inputs.
Count the ways to cut items into three non-empty consecutive parts items[:i], items[i:j], items[j:] (with 1 <= i < j <= n - 1) that all have the same sum. If the total is not divisible by 3 the answer is 0. Otherwise let t = total // 3: you need prefix[i] == t and prefix[j] == 2 * t, with i < j. Walk j from left to right, keep a running count first_cuts of the positions i < j with prefix[i] == t, and each time prefix[j] == 2 * t add first_cuts. Write three_parts_truth (tries every cut pair), three_parts, three_parts_product (multiplies the number of t-positions by the number of 2t-positions, ignoring order) and three_parts_empty_middle (lets i == j). Zeros and negatives must work. Fuzz on 2,000 seeded arrays.
A string contains only the letters a, b and c. Count the substrings in which the three letters appear the same number of times (substrings are non-empty, so each letter appears at least once; "abc" counts). Track running counts pa, pb, pc. A substring between two positions is balanced when pa, pb and pc all grew by the same amount, which means the pair (pa - pb, pb - pc) is unchanged. Use that pair as a dict key, count how many earlier positions had each key, and add that count at each step. Write balanced_truth, balanced_count, and balanced_one_key, which uses only pa - pb and so counts substrings where a and b match but c does not. Say which seed form you use. Fuzz on 2,000 seeded strings.
Numbers arrive one at a time. Build a class ProductOfLast with add(num) and get(k), where get(k) returns the product of the last k numbers added (k never exceeds how many have been added). Keep prefix products prefix starting at [1]. Division gives the answer: prefix[-1] // prefix[-1 - k] (exact for integers). A zero breaks this, because every later prefix is 0 and you cannot divide by it. So on add(0) reset prefix to [1], and in get(k) return 0 when k reaches back past the reset, which means a zero is inside the last k. Write ProductOfLastTruth (keeps every number), ProductOfLast, and ProductNoReset, which never resets. Run 300 seeded operation sequences and count the wrong answers and crashes of the no-reset version. Comment that Python ints do not overflow and what C would need.
A prefix array is for static data. When items[i] changes, every prefix after i is out of date. Compare three designs on a workload where an update and a range-sum query alternate. STEP 1: RebuildPrefix (a prefix array goes stale after an update, so it must rebuild) rebuilds the whole prefix array on each update, O(n) per update and O(1) per query. STEP 2: SqrtBlocks splits the array into blocks of size about sqrt(n) (use math.isqrt), keeps one sum per block in plain lists, and gives O(1) update and O(sqrt n) query (a partial block at each end, whole blocks in between). STEP 3: fuzz RebuildPrefix and SqrtBlocks against a brute-force sum on 300 seeded runs. STEP 4: time 500 alternating update/query pairs with best_of(fn, repeats=3) for n = 1000, 2000, 4000, print the table and the growth factor of each column computed from the measured times, then time 500 queries with no updates at n = 4000 for both designs, and finish with one comment naming Fenwick trees and segment trees as the production answer (this track does not build them).
Given a list a of numbers and many query values q, return sum(abs(x - q) for x in a) for each q. The direct sum is O(n) per query. Sort a once with sorted() and build a prefix array. For a query q, bisect_left(a_sorted, q) gives idx, the count of values below q. Those idx values contribute q * idx - prefix[idx], and the other n - idx contribute (prefix[n] - prefix[idx]) - q * (n - idx). Write distances_truth, distances and distances_unsorted, which builds the prefix and calls bisect_left without sorting. Fuzz on 2,000 seeded inputs with negative values, then time 100 and 1,000 queries on n = 2000 with best_of(fn, repeats=3).
Ten problem statements, each described by its shape (what is asked) and its operation (what is combined). Write route(shape, operation) that returns one of "prefix", "prefix + dict", "difference array", "2-D", "window" or "not possible (no inverse)", using these rules: sum and xor have an inverse (subtract, xor again), while max, min and gcd do not, so prefix and difference tricks fail for them. Shapes are range_queries (many questions about items[l..r]), count_subarrays (how many subarrays have sum equal to k, or a remainder equal to r), range_updates (many adds on ranges, read at the end), rect_queries, rect_updates, and window (a window that grows and shrinks, or a fixed length, over non-negative values). Print the table with the deciding property, assert it matches the expected routing, and then show with one example why prefix subtraction fails for max.
An employee's hours list holds the hours worked each day. A day is tiring when the hours are strictly more than 8. An interval of consecutive days is well-performing when it has strictly more tiring days than non-tiring days. Find the length of the longest well-performing interval (0 if there is none).
The array has no sign to start with, so map each day to +1 (tiring) or -1 (not), which turns "more tiring than not" into "the sum is greater than 0". Then use a first-occurrence map first of prefix scores. Only the score prefix - 1 needs a lookup, not every smaller score. Write well_truth (brute force) and well, and check them on the example [9, 9, 6, 0, 6, 6, 9] and on 2,000 seeded inputs. Then write two broken variants, one that looks up prefix instead of prefix - 1 and one that overwrites first on every sighting, and print where each goes wrong. In comments, say which seed form you use and why, and prove why looking up prefix - 1 is enough.
Remove the shortest contiguous subarray (it may be empty, but it may not be the whole array) so that the sum of what remains is divisible by p. Return the length removed, or -1 if no such removal exists.
Let need = total % p. You must remove a subarray whose sum has remainder need. Walk the prefix remainders with a dict, and look up the remainder (current - need) % p. The question asks for the shortest removal, so the map must keep the latest index of each remainder. Write shortest_removal_truth and shortest_removal, fuzz them on 2,000 seeded inputs, then show what happens if the map keeps the first index instead.
Count the rectangular sub-grids of grid (integers, negatives allowed) whose cells add up to target. A 2-D prefix table with four loops costs O(r^2 * c^2). Do better by fixing a pair of rows, top and bottom: squash those rows into one list of column sums, and every rectangle between those rows is now a 1-D subarray of that list. Count the subarrays with sum target using a dict of prefix sums, exactly as for "subarray sum equals k".
STEP 1: write count_submatrices_truth (direct sums, tiny grids only) and count_submatrices (row pairs plus the dict), and fuzz them on 400 seeded grids. STEP 2: show that dropping the {0: 1} seed from the 1-D counter loses rectangles that start at column 0. STEP 3: time the four-loop 2-D prefix solution against the row-pair solution on a 36 x 36 grid. Comment on the seed form and the complexity.
Given a fixed list items, answer many queries "how many times does value v appear in items[left..right]?". Two designs are on the table.
Design A keeps, for every distinct value, a prefix-count array over the whole list: a query is one subtraction. Design B keeps, for every distinct value, the sorted list of positions where it occurs: a query is two bisect calls. Build both, check them against a brute-force count, and measure the memory (sys.getsizeof of every list the design holds) and the query time on two inputs of the same length: one with 4 distinct values and one with 1,000. Choose a design for each input against a stated memory budget of 256 KiB, using the printed memory numbers.
A table is a string s of '*' (a plate) and '|' (a candle). A query (left, right) asks how many plates lie between candles inside s[left..right]: only plates with a candle somewhere to their left and a candle somewhere to their right, both inside the range, count.
Build a prefix count of plates, and two arrays from two scans: next_candle[i] (the nearest candle at index >= i, or n if none) and prev_candle[i] (the nearest candle at index <= i, or -1 if none). A query then snaps left rightward and right leftward to candles and subtracts. Check against a brute force on seeded queries, show what happens if you skip the snapping, and time 2,000 queries on a 3,000-character table against the per-query scan.
A shop's log customers is a string of 'Y' (a customer arrived that hour) and 'N' (nobody did). If the shop closes at hour j (from 0, closed all day, to n, open all day), the penalty is the number of 'N' hours it was open (indices below j) plus the number of 'Y' hours it was closed (indices j and above). Return the closing hour with the smallest penalty, the earliest one on a tie.
Write best_close_truth (recount at every j), best_close (a prefix count of 'N' and a suffix count of 'Y') and best_close_scan (one pass with O(1) extra space, moving j one step at a time). Fuzz all three on 2,000 seeded logs, then show what happens if the tie-break comparison is <= instead of <.
For each element of nums, compute the sum of abs(nums[i] - nums[j]) over all j. The naive version is O(n^2). If nums is sorted, the absolute values can be dropped: every earlier element is <= nums[i] and every later one is >=, so the answer is nums[i] * i - (sum of the i earlier elements) plus (sum of the later elements) - nums[i] * (n - 1 - i). Both sums come from one prefix array.
Write distance_sums_truth and distance_sums_sorted, then distance_sums for unsorted input (sort the indices once, compute on the sorted order, and write each answer back to its original position). Fuzz them on 2,000 seeded inputs with duplicates and negatives, show what the sorted-only version prints when fed an unsorted list, and time all three at n = 3,000.
Count the subarrays of items that are interesting for the parameters (modulo, k): let cnt be the number of elements x in the subarray with x % modulo == k. The subarray is interesting when cnt % modulo == k.
Turn each element into a 0/1 indicator and take a prefix of the indicators, reduced % modulo as you go. A subarray ending at the current position is interesting when (current - earlier) % modulo == k, so the earlier prefix you need has remainder (current - k) % modulo. Count with a dict. Write count_interesting_truth and count_interesting, fuzz 2,000 seeded inputs (including modulo = 1), and show two broken variants, one with the wrong sign (current + k) and one that forgets the % modulo on the lookup key. In comments, say which seed form you use, and why two prefix remainders that differ by k mark a valid subarray.
Find the length of the longest substring of s (lowercase letters) in which each of the vowels a, e, i, o, u appears an even number of times (zero counts as even). Other letters are unrestricted.
Sliding window (Topic 5) cannot do this: adding or removing one character flips a parity, so "valid" does not move steadily as the window grows or shrinks and there is no rule for which side to shrink. Prefix sums can: keep a 5-bit parity mask of the prefix, where bit b is 1 when vowel b has appeared an odd number of times so far.
STEP 1: write longest_even_truth and longest_even (mask plus a first-occurrence dict) and check the example "eleetminicoworoep" and 2,000 seeded strings. STEP 2: print the masks along the way for a short string. STEP 3: write two broken variants, one with first = {} (no seed) and one that overwrites the stored index, and print where each fails. Comment on the seed form and say why two equal masks mean a valid substring.
A string over the letters a to j is wonderful when at most one letter appears an odd number of times. Count the substrings of s (counted by position, so equal substrings at different places count separately) that are wonderful.
Use the same parity mask as for "every count even", with 10 bits. Two prefixes with the same mask give an all-even substring. A substring with exactly one odd letter comes from two masks that differ in exactly one bit. For each new prefix mask, add the stored count of that mask plus the stored counts of its 10 one-bit neighbours (mask ^ (1 << b)). Write count_wonderful_truth and count_wonderful, check the example "aba" and 1,000 seeded strings, show that matching only the same mask misses the one-odd substrings, and time both at a size that suits each. Comment on the seed form and say why a one-bit difference means exactly one odd letter.
Given a grid of integers and a threshold, find the largest side s such that some s x s square of the grid has a sum <= threshold. Return 0 if even a single cell is too big. A square of side s is tested in O(1) from a 2-D prefix table P, and when every value is non-negative a bigger square always contains a smaller one, so "some square of side s fits" can only turn from true to false as s grows. That makes the side length a search space for binary search (Topic 3). Write largest_side_truth (try every side), largest_side (binary search on the side) and fuzz them on 1,500 seeded non-negative grids. Then fuzz both on grids with negatives and print how often the binary search is wrong, with the smallest failing grid.
A box blur replaces every pixel by the integer mean (floor division) of its (2k+1) x (2k+1) neighbourhood, where the neighbourhood is clamped at the borders, so a corner pixel averages only the pixels that exist. Write blur_naive (loop over the neighbourhood), blur (2-D prefix table, four corners, divide by the clamped window area) and blur_fixed_divisor (divides by (2k+1)^2 everywhere). Print a 5 x 5 example for k = 1, show the border pixels the fixed divisor gets wrong, fuzz on 1,000 seeded grids, and time naive against prefix on a 60 x 60 image for k = 1, 3, 6 with best_of(fn, repeats=3).
A hotel has n days numbered 0..n-1. Each booking is (first, last, guests): guests people stay on every day from first to last inclusive. Find the busiest day: the largest number of guests present on one day, and the earliest day on which that happens. Write busiest_naive (add guests to every day of every booking), busiest (a difference array: diff[first] += guests, diff[last + 1] -= guests, rebuild with a running sum, then take the max and its first index), and fuzz them on 1,000 seeded inputs. Then show two traps on the same example: scanning >= instead of > returns the last busiest day, and taking max(diff) without rebuilding answers a different question. Time naive against difference for 200, 400 and 800 bookings over 5,000 days with best_of(fn, repeats=3). Label your code with # STEP 1:, # STEP 2:, and so on.
You are given inclusive integer ranges [a, b] on a line of points 0..M. Count the points that are covered by at least k ranges. Use a difference array, rebuild the coverage with a running sum, and count the points whose coverage is >= k. Write covered_truth (add 1 to every point of every range), covered_at_least and covered_half_open (a bug: it writes diff[b] -= 1, treating the end as exclusive). Check the first on the example below, print the coverage array, and fuzz on 1,500 seeded inputs. Show that k = 1 gives the union length. Say in a comment what happens when coordinates reach 10^9 and which later topic (Topic 9's sweep) fixes it.
A grid holds 0 for an empty cell and 1 for a blocked cell. You own unlimited stamps of size h x w. A stamp may be placed anywhere that stays inside the grid and covers only empty cells; stamps may overlap, and may not be rotated. Return True if every empty cell can be covered by at least one stamp. Build a 2-D prefix table over the blocked cells to find every legal top-left corner in O(1) each, then use a 2-D difference array (four corner writes per stamp) to mark all coverage at once, rebuild it with a 2-D running sum, and check every empty cell. Write can_stamp_truth (stamp cell by cell into a set), can_stamp, and can_stamp_any_fit (a bug: it only checks that at least one stamp fits). Fuzz on 2,000 seeded grids and print a counter-example for the bug.
Items sit on a circle of n positions. A query (start, end) asks for the sum of the items going clockwise from start to end, both inclusive. When start > end the range wraps through position n - 1 back to 0. When start == end + 1 the wrapped range is the whole circle. Write circular_truth, then two O(1) answers after a linear build: circular_doubled (a prefix array over items + items, which has 2n + 1 entries) and circular_complement (total minus the range that was left out), and circular_no_wrap (a bug: it uses the plain formula even when start > end). Fuzz on 2,000 seeded inputs with negatives, print some wrapped queries beside the bug, and compare the memory of the two prefix arrays.
Find the largest sum of any non-empty contiguous subarray of items (negatives allowed), and the left/right it spans. Every subarray ending at right has sum prefix[right + 1] - prefix[left], so the best one ending at right subtracts the smallest earlier prefix. Walk once, keeping the smallest prefix seen so far, and take the best difference. Write max_subarray_truth (all pairs), max_subarray and two buggy variants: max_subarray_update_first (updates the minimum before using it) and max_subarray_best_zero (starts best at 0). Check the three on [-3, -1, -2] and on [2, -5, 4, -1, 3, -6, 2], and fuzz on 2,000 seeded inputs that include all-negative arrays. Say in a comment that this one-pass idea is the same as Kadane's algorithm, which DSA Topic 21 names. Label your code with # STEP 1:, # STEP 2:, and so on.
Count the pairs (left, right) with left <= right whose range sum lies in [lo, hi] (negatives allowed). In prefix terms: count pairs of prefixes earlier < later with lo <= prefix[later] - prefix[earlier] <= hi. Write count_in_range_truth (slice sums, tiny inputs), count_pairs (O(n^2) over prefix pairs) and count_sorted_list, which keeps the earlier prefixes in a sorted list and uses bisect_left/bisect_right for the count and bisect.insort for the insert. Comment the seed form and why you query before you insert. Fuzz them, show what happens if you insert first, time the two for n = 500, 1000, 2000 with best_of(fn, repeats=3), and print one run at n = 20,000. State the honest cost of insort and name merge-sort counting (Topics 8 and 9) as the O(n log n) answer.
Prefix subtraction assumes prefix[right + 1] - prefix[left] recovers the range exactly. With floats it does not: once a prefix is huge, adding a small number rounds it away, and the later subtraction cannot bring it back. First show a hand case with [1e16, 1.0, 1.0, 1.0], where the range 1..3 should be 3.0. Then build 2,000 amounts in cents (random 1 to 999, with three entries equal to 10^17 cents, i.e. 10^15 dollars), convert them to float dollars, and answer 300 seeded range queries after the last big entry in three ways: float prefix subtraction, math.fsum of the slice, and integer cents in a prefix array divided by 100 at the end. Print the largest error and the number of wrong answers for each, then conclude which fix you would use and why.
Eight workloads are described below. Write choose(workload) that returns one of "nothing", "prefix", "difference", "2-D prefix", "prefix + dict", "sqrt blocks", "sliding window" or "no inverse: other structure" from the declared fields of the workload, and assert that it picks the expected answer for all eight. Then measure on a list of 2,000 integers the cost of a naive range sum, a prefix build, a prefix query, a square-root-block update and a block query (use best_of(fn, repeats=3) on batches). Derive from those same numbers (1) how many queries it takes before building a prefix beats naive summing, and (2) how many updates per query a full prefix rebuild can afford before square-root blocks win. Name Fenwick and segment trees as what production code uses for (2), without building them.
The eight workloads: (a) one range sum on a list; (b) 100,000 range sums on a list that never changes; (c) 50,000 range additions followed by a single read of every position; (d) interleaved point updates and range sums; (e) count the subarrays that sum to k; (f) rectangle sums on a fixed grid; (g) the longest subarray with sum <= k where every value is non-negative; (h) range-maximum queries on a fixed list.
Two seeds look alike and mean different things. In the count form, seen = {0: 1} says "the empty prefix has been seen once". In the index form, first = {0: -1} says "the empty prefix ends just before index 0". A developer copies the seed from one solution into the other. Write count_index_seeded (a counter seeded with {0: -1}), longest_count_seeded (a longest-subarray solver seeded with {0: 1}) and longest_zero_seeded (seeded with {0: 0}), next to the correct count_sum_k and longest_sum_k. Fuzz all five against count_sum_k_truth and longest_sum_k_truth with a harness that counts a raised exception as a failure. Use an exhaustive sweep of short lists plus seeded random lists. Print the smallest failing input for each bug. Then prove the diagnosis. For the counter, the wrong answer must equal truth - 2 * z exactly, where z is the number of prefixes items[0..right] that sum to k. For the longest solvers, the answer must be wrong exactly when every longest subarray with sum k starts at index 0.
This "longest subarray with sum k" solver passes every test its author wrote, and the tests all used positive numbers:
def longest_overwrite(items, k):
first = {0: -1}
total = best = 0
for right, x in enumerate(items):
total += x
if total - k in first:
best = max(best, right - first[total - k])
first[total] = right
return bestThe fix (keep the earliest index) is known. This question is about predicting the bug. The map ends up holding the latest index of each prefix value, so state in one sentence what longest_overwrite really computes. Use that sentence to predict, by hand, its output on five inputs: [1, 2, 3] with k = 3, [0, 0, 1] with k = 1, [2, -2, 3, 1, -1] with k = 3, [1, -1, 1, -1] with k = 0 and [5, 0, 0] with k = 5. Write the predictions into the code before running anything, then print each one beside the buggy output and the truth. Confirm the sentence as an identity, using a brute-force max_of_shortest_truth on an exhaustive sweep plus seeded lists. Finally, explain why positive-only tests cannot see the bug. Show that it needs a repeated prefix value, and use [5, 0, 0] to show that a repeat alone is not enough.
Three typos of the range formula prefix[right + 1] - prefix[left] are common: prefix[right] - prefix[left], prefix[right + 1] - prefix[left + 1] and prefix[right + 1] - prefix[left - 1]. None of them raises. First show a hand-written test, [0, 0, 5, 0] with the query (1, 3), that all three pass. Then fuzz every query on seeded lists, and print each typo's failure rate and its smallest failing case. Prove what each typo actually computes: give its exact error wrong - truth as a formula in the items, and check that formula on every query. For the left - 1 typo, explain what prefix[-1] silently reads when left == 0.
A difference array for n positions needs n + 1 slots, because diff[right + 1] -= v writes one past the last position when right == n - 1. Four people built it with only n slots. apply_short crashes with IndexError. apply_skip guards the whole update with if right + 1 < n. apply_wrap writes diff[(right + 1) % n]. apply_guard_end guards only the second write. Fuzz all four and the correct apply_updates against apply_truth (naive range loops), with a harness that counts a crash as a failure. Then prove each diagnosis exactly. apply_short raises exactly when some update has right == n - 1. apply_skip returns the truth for the list with those updates removed. apply_wrap returns the truth minus S at every position, where S is the total v of those updates. And apply_guard_end is correct. Say why n + 1 is still the convention.
You are porting a "count subarrays whose sum is divisible by k" solution from Java, where a % b takes the sign of a. Emulate that remainder exactly with integers as c_rem. Then show that math.fmod and int(a / b) give the same remainder for small values but go through floats, so they are wrong for large integers. Write four counters: count_divisible (Python's %), count_c_style (raw c_rem), count_abs_fix (a tempting "fix", abs(c_rem(...))) and count_ported_fix (c_rem(c_rem(a, k) + k, k)). Fuzz them against count_divisible_truth with a harness that counts a crash as a failure, and print the smallest failing input for each wrong counter. Then prove the diagnosis. Show that the C-style count is short by exactly the number of prefix pairs that share a residue class but get different keys. Show that it never fails when every prefix is non-negative. Explain why abs merges two different classes.
A report builds prefix from a list of sales. Later, another part of the program corrects sales[i] in place, and the report keeps answering range queries from the old prefix. Show the silent wrong answers. Prove that every stale answer equals the answer for the old list exactly, and that a query is wrong exactly when left <= i <= right and the correction is non-zero. Then design RangeSums. It owns a private copy of the data, changes it only through set(i, value), and keeps a version counter that queries check. Give it three policies: rebuild on every set, patch prefix[i + 1:] by the delta, and a lazy rebuild before the first query after a change. Fuzz all three against a brute force. Finally, time them on three workloads (alternating, bursts of updates, and corrections near the end), and pick each winner from the printed numbers.
A developer who knows the XOR trick writes range OR from a prefix-OR array por. Three versions are in circulation: or_by_xor (por[right + 1] ^ por[left]), or_by_minus (por[right + 1] - por[left]) and or_from_start (por[right + 1]). Print their wrong answers beside the truth, and count the failures over every query on seeded lists. Explain why or_by_xor, or_by_minus and por[right + 1] & ~por[left] always give the same number. Then prove that no formula over the prefix array can work, for OR, max or gcd. Search small lists for two different lists with the same prefix array whose range answers differ. Show that for + and XOR, the prefix array determines the list, so no such pair exists. Fix range OR with per-bit prefix counts, a prefix sum that does have an inverse. Fix max and gcd with square-root blocks, and fuzz the fixes.
The correct rectangle query is P[r2 + 1][c2 + 1] - P[r1][c2 + 1] - P[r2 + 1][c1] + P[r1][c1], and the table is built with - P[r][c]. Four broken versions are in circulation. minus_corner subtracts the add-back corner. forgot_plus_one uses P[r2][c2], P[r1][c2], P[r2][c1]. top_off_by_one uses - P[r1][c2] in place of - P[r1][c2 + 1]. build_plus builds the table with + P[r][c]. For each one, search 0/1 grids in order of size, then number of ones, and print the minimal failing grid and query. Then prove each diagnosis with an exact identity checked on seeded random grids. minus_corner is off by -2 * P[r1][c1]. forgot_plus_one returns the sum of rows r1..r2-1, columns c1..c2-1. top_off_by_one adds the cells of column c2 above row r1. build_plus fails only on grids with at least 2 rows and 2 columns.
These three builders all return the right prefix array:
prefix = [sum(items[:i]) for i in range(n + 1)] # build_slices
prefix = prefix + [prefix[-1] + x] # build_concat, inside a loop
prefix.append(prefix[-1] + x) # build_running, inside a loopShow that they agree. Then count the work: write counted copies of the builders that add up the existing elements each one reads to make a new entry, and check the counts of build_slices and build_concat against n(n + 1) / 2. Time all three plus itertools.accumulate with best_of for n = 1000, 2000, 4000, 8000. Print the growth exponent e in time ~ n^e, fitted over the whole range, and explain which builds are quadratic and why prefix + [...] is one of them.
In the count form of "subarrays with sum k", the loop must query seen[prefix - k] and only then insert the current prefix. Write count_insert_first, which swaps the two lines. Fuzz it against count_sum_k_truth with a harness that counts a crash as a failure, and show that it fails only when k == 0. Prove the exact error: wrong == truth + n when k == 0, and wrong == truth otherwise. Then do the same swap in the divisible-by-k counter and in the longest-subarray solver. Show that the divisible counter is wrong on every non-empty input, by exactly n, and that the longest solver is never wrong. Finish with a proof sketch of "query, then insert": an invariant on what seen holds at the moment of the query.
Three edges break otherwise-correct prefix code: k = 0 ("sum equals 0"), "divisible by 0" (a crash waiting to happen), and the empty input. Decide what each should mean, write the decision down, and make the code and an oracle agree with it. Build count_sum_k(items, k), count_divisible(items, k) and longest_sum_k(items, k). Show a table of edge cases, show the crash from a naive total % k at k = 0, and fuzz 1,500 seeded cases (k from -3 to 3, lengths 0 to 8). The fuzz must catch exceptions and count them as failures.
Python integers never overflow, so prefix-sum code that is correct here can be wrong when ported to C or Java, where an int is 32 bits. Emulate int32 with wrap32(x) (two's-complement wrap-around, using masking) and rebuild the prefix array with every addition wrapped. Show on [10**9] * 5 how the wrapped prefix values turn negative, which range answers survive and which do not, and how a bisect on the wrapped prefix goes wrong. Then fuzz 3,000 seeded queries and print how many were right, how many were wrong, and in how many the prefix overflowed yet the answer was still right. Finish by moving to 64 bits and showing that this only moves the cliff.
A 2-D prefix table P has (rows + 1) * (cols + 1) entries, and in Python each entry is a pointer to an int object. Measure it: write a deep_size that adds sys.getsizeof of the outer list, every row, and every distinct integer above 256 (small ints are shared singletons that are not specific to your table). Build seeded grids of 10x10, 20x20, 40x40, 80x80 and 160x160, print bytes per cell, then predict the size of a 400x400 table from the 160x160 number and compare it with the measured one. Extrapolate to 5,000 x 5,000 without building it. Finally compare three ways to answer a 100x100 rectangle sum on a 400x400 grid: the full table, row-wise prefixes, and the raw grid summed on demand. Print bytes and lookups for each, time the two builds with best_of, and check that all three agree on 50 seeded queries.
A prefix array that is "kept fresh" can hide an O(n) rebuild inside the query path. Here is the trap: EagerQuery.query calls accumulate before every lookup "to be safe". The query line reads like O(1), and no update ever has to touch the prefix, so it passes every test. Find it, measure it, and fix it two ways. (1) Write EagerQuery and count its rebuilds with a rebuilds counter. (2) Run a workload with no updates at all and time the per-query cost as n doubles. (3) Fix it with a dirty flag (DirtyFlag: rebuild only after an update, and only when a query needs it). (4) Show the flag's limit: on strictly alternating update / query it rebuilds every time again, so write Blocks (square-root blocks, plain lists) as the second fix. Time all three on three workloads (queries only, a burst of 10 updates then queries, alternating), check that every answer agrees, and fuzz 600 small seeded cases (exceptions count as failures).
The bugs in this band are all the same kind: code that looks right and passes a hand-picked example. Build one differential harness that catches each of them by name. Write a correct function, a buggy function and a brute-force oracle for each of seven bugs: (1) a missing {0: 1} seed, (2) overwriting the first occurrence in a longest-subarray map, (3) prefix[right] instead of prefix[right + 1], (4) a difference array with n slots instead of n + 1, (5) a C-style remainder (math.fmod) in the divisible-by-k count, (6) range OR by prefix subtraction, where OR has no inverse, and (7) a wrong sign in the 2-D rectangle. The harness runs the buggy function on seeded random inputs, counts every mismatch and every exception as a failure, keeps the smallest failing input, and also runs the correct function as a control that must score zero. Print a catch table, then repeat on three seeds so it cannot pass by luck.
Label the steps # STEP 1: and so on.
Build a RangeQueryService class. It builds its tables once from a list of integers and a predicate, then answers four range queries in O(1): sum, xor, count (how many items satisfy the predicate) and floor_average (sum divided by length, rounded toward negative infinity). Every query takes an inclusive (left, right) and validates it: non-integers raise TypeError, an index outside 0..n-1 raises IndexError (negative indices are rejected, never wrapped), and left > right raises ValueError. Demo it, including the errors. Fuzz it against a brute-force service_truth on 2,000 seeded queries that include invalid ones, with exceptions caught and compared by class. Benchmark it against answering each query by scanning, using best_of, and print the break-even number of queries from the same measurements.
Build a BudgetTracker(opening, ledger, months) where ledger is a list of (month, amount) pairs sorted by month (income positive, spending negative). From one prefix array it answers: the balance after any transaction, the first overdraft (index of the first transaction that leaves the balance below zero, or None), the minimum opening balance that avoids any overdraft, each month's total and closing balance (months may have no transactions), and the worst month. Demo it on a seeded year, and check the minimum-opening claim by trying min_opening and min_opening - 1. Fuzz 800 seeded ledgers (including empty months and empty ledgers) against a brute-force tracker_truth, with exceptions counted as failures.
An integral image is a 2-D prefix table over pixel brightness. Build a seeded 16 x 40 ASCII image (brightness 0 to 9, a bright rectangle on a noisy dark background), print it with a character ramp, and use the table to evaluate two-rectangle (Haar-style) features in O(1): a vertical-edge feature (right half minus left half) and a horizontal-edge feature (bottom half minus top half). Scan the image band by band, find the strongest rising and falling edge in each band, and print the detections. Fuzz the integral feature against a naive pixel sum on 200 seeded images (exceptions count as failures), and time both on an 80 x 80 image with best_of.
Build a BookingBoard(capacity) over the 1,440 minutes of a day. book(start, end) takes minutes as a half-open range [start, end) and records it in a difference array with two writes. The board answers: the occupancy of every minute (rebuilt lazily after bookings change), the overbooked intervals (occupancy above capacity), the peak occupancy with the first minute it happens, and the free slots of at least a given length inside a working window. Validate bookings (0 <= start < end <= 1440, otherwise ValueError). Demo it on 14 seeded bookings with a one-line strip, and fuzz 500 seeded boards, including bookings that touch minute 0 and minute 1440, against a minute-by-minute board_truth (exceptions count as failures).
Build a TextStats engine over a text of integer symbols 0..A-1 (letters are symbols with A = 26), with two interchangeable backends for "how many times does symbol s appear in text[left..right]" (inclusive): PrefixBackend keeps one prefix-count array per symbol (A arrays of length n + 1), and PositionBackend keeps one sorted list of positions per symbol and counts with bisect. Both support count, most_common(left, right) (ties go to the smallest symbol) and same_letters(a_left, a_right, b_left, b_right) (do two ranges have the same symbol counts). Demo on a short seeded letter string. Then make the measured comparison as the alphabet grows: A = 26, 256, 4096 on a seeded text of 1,000 symbols. For each A fuzz both backends against list.count (exceptions count as failures), measure deep memory and best_of time for single count queries and for most_common (which makes A backend calls), and compute from those numbers where the trade-off flips against a stated 16 MB memory budget.
Build an ElevationProfile for a hiking track. The track has n segments: lengths[i] is the horizontal length of segment i in metres, and elevation has n + 1 entries, the height at each checkpoint (checkpoint i is the start of segment i). Build three prefix arrays with itertools.accumulate(..., initial=0): cumulative distance, cumulative gain (the climbs only) and cumulative loss (the descents only). Then answer:
stretch(a, b): the distance, gain, loss and net change from checkpointato checkpointb(witha < b), each in O(1). Reject bad checkpoints with aValueError.steepest(min_metres): the stretch with the steepest average climb, among the shortest stretch starting at each checkpoint that covers at leastmin_metres. The distance prefix is increasing, sobisect(Topic 3) finds each end. Compare gradients exactly with integer cross-multiplication, and take the earliest start on a tie.
Write stretch_truth and steepest_truth that walk the segments one by one. Demo the tool on a seeded 40-segment track, and fuzz it on 500 seeded tracks, counting any exception as a failure. Time 300 queries on a 50,000-segment track against the walking version with best_of. State the time and space complexity of every method.
Every "count the subarrays with property P" problem in this topic has the same shape: walk once, carry a running prefix state, turn each state into a dict key, and ask how many earlier prefixes had the key that would make the subarray between them qualify. Build that shape once as
count_by_key(items, step, key_of, target_key, start=0)
step(state, x)returns the next prefix state (the running sum, the running XOR, a tuple of letter counts).key_of(state)is the key this prefix is stored under.target_key(state)is the key an earlier prefix must have for the subarray between them to qualify.startis the state of the empty prefix. The seed is{key_of(start): 1}.
Plug in four problems: sum equals k, sum divisible by k, XOR equals k, and balanced letters (a string over abc with equal numbers of each letter). Write a brute-force <name>_truth for each, and fuzz all four on seeded inputs, counting any exception as a failure. Then show what goes wrong if the engine is seeded with the literal {0: 1} instead of the key of the empty prefix. Finish by timing the engine against a brute force with best_of. Comment the seed form and the complexity.
Build a small fuzzing tool for prefix-based solvers of "count the subarrays with sum equal to k". It has three parts:
- a generator of seeded
(items, k)cases, including empty lists, zeros and negatives; - an oracle,
count_sum_k_truth, the O(n^2) brute force; a case fails when the solver's answer differs from the oracle's or the solver raises; - a shrinker that takes a failing case and makes it smaller while it still fails: delete one item, halve one value toward 0, or halve
ktoward 0. Each accepted move must strictly reduce the measure(len(items), sum of abs values, abs(k)), so the shrinker always stops.
Run it on three solvers: a correct one; one with a seeded bug that keeps the seen prefixes in a set instead of counting them; and one that crashes on an empty list. For each solver, print the failure count, the first failing case, its shrunk form and the number of shrink steps. For the set bug, print the prefix array of the shrunk case and show why it fails. State the complexity of each part.
Build a HeatmapPainter for a grid of rows x cols cells. paint(r1, c1, r2, c2, weight) adds weight to every cell of the inclusive rectangle, in O(1), by touching the four corners of a (rows + 1) x (cols + 1) 2-D difference array. render() rebuilds the heat with a 2-D running sum. Add:
ascii(): one character per cell from the ramp" .:-=+*#%@", scaled so the hottest cell is@;hottest(): the largest heat and its cell, earliest in row-major order on a tie.
Reject rectangles that leave the grid. Write paint_truth, which adds the weight cell by cell. Demo the painter on 15 seeded rectangles over a 12 x 36 grid and print the heatmap. Fuzz it on 400 seeded grids, counting exceptions as failures. Then time 500 large rectangles and 5 one-cell rectangles on a 200 x 200 grid with best_of. State the complexity.
Point updates and range-sum queries arrive interleaved. Benchmark three structures behind the same update(i, value) / query(left, right) interface:
- Naive: a plain list. Update O(1), query O(n) with
sumof a slice. - Prefix: a prefix array rebuilt with
accumulateafter every update. Update O(n), query O(1). - Blocks: square-root blocks, with one sum per block of about
sqrt(n)items. Update O(1), query O(sqrt n).
Fuzz all three against a brute force (query_truth) with random.Random(6), counting exceptions as failures. Then, with n = 10,000 and 500 operations per row, time each structure (best_of, min of 3) on six workloads whose update share is 0%, 1%, 10%, 50%, 90% and 100%. Every structure gets the same operation list in a row. Print the table. Draw the conclusion only from the numbers in that table: for each row, which structure was fastest and by how much over the runner-up; for each structure, its worst ratio to the fastest in any row; and where the prefix array stopped winning. A margin under 1.5x should be reported as close, not as a win.
An interviewer says: "Explain prefix sums and difference arrays to me as if I had never seen them, and show me the three things people get wrong." Write the answer as code plus a printed script. It should cover:
- why the prefix array has n + 1 entries, traced on a small array, with the length-n version's special case shown;
- the difference array as the inverse of the prefix: the prefix of the differences gives the array back, and a range add is two writes;
- the inverse rule: subtraction of prefixes works for
+and XOR, and gives a wrong answer formax(print it); - the seed for counting subarrays: why it is
{0: 1}for counting, and{0: -1}(first index) for the longest. Show the count without the seed going wrong.
Check every claim on seeded inputs against a brute force, and end with the complexity of each piece.
An interviewer hands you five prefix-based functions. Each passes the example in its docstring and each has one bug. The rule of the exercise: read the code, name the bug, and write down the smallest input you predict will fail, together with the wrong answer you expect, before running anything. Only then run it to confirm. The five:
range_sumthat returnsprefix[right] - prefix[left].count_sum_kseeded with an empty dict.longest_sum_kthat stores the latest index of each prefix.count_sum_kthat inserts the current prefix before looking upprefix - k.count_divisiblethat takes remainders the C/Java way (int(math.fmod(a, k))).
For each, print the reasoning, the prediction, the actual output, the truth, and whether the prediction held. Then fuzz each bug on 1,000 seeded inputs, to show how often it fails and which inputs trigger it. State the complexity of the correct version of each.
The interviewer: "We keep 20,000 daily stock counts and answer range-sum queries on them. Each day, corrections arrive as a batch of range adds ('add v to every count from left to right'), then the day's 20 queries run. Design it." Write the conversation as code plus a printed script:
- clarifying questions, then the brute force and its costs;
- design A, a difference array: each add is two writes, and one rebuild of values and prefix per batch, then O(1) queries;
- design B, square-root blocks with a pending add per block: a range add touches at most two partial blocks item by item and tags the whole blocks between them, O(sqrt n), and queries are O(sqrt n);
- verify both against a brute force on seeded days;
- measure the unit costs, compute the break-even batch size from them, and check the choice on batches of 5 and 1,000 adds, each far from the break-even, so noise cannot flip the verdict;
- edge cases: an empty array,
nthat is not a perfect square (a short last block), and a correction that changes nothing (v = 0); - what production code would use, named but not built.
A mock interview, written as a transcript that runs. The opening problem is "count the subarrays whose sum equals k", with negatives allowed. Follow the arc: clarify, brute force, the prefix + dict solution, why it is correct, complexity, and edge cases. Then answer the interviewer's four follow-ups, each with code checked against a brute force on seeded inputs:
- The longest such subarray instead of the count.
- The count of subarrays whose sum is divisible by k.
- The 2-D version: count the submatrices of a grid that sum to k.
- Streaming: the numbers arrive one at a time. After each arrival, report the running count. Then, as a twist, count only subarrays of length at most
W, so old prefixes must be forgotten.
Comment the seed form of every dict and the complexity of every function.
The capstone: build a range analytics engine. A caller declares a workload: the shape (1-D or 2-D), the operation (+, xor or max), what is read (ranges, rectangles, or "count / longest subarray summing to k"), what kind of updates arrive (none, point updates mixed with reads, or a batch of range adds before the reads), and how many of each. The engine chooses a structure from that declaration, explains the choice in one line, and then serves every operation through one method, apply(op). It must:
- Use the n + 1 prefix with
prefix[0]as the identity, for static range reads, and refuse prefix subtraction for an operation with no inverse (max). Print the wrong answer subtraction would give. - Use a difference array for a batch of range adds, then a prefix over the rebuilt values for the reads.
- Use a 2-D prefix for rectangle reads, and refuse the 2-D prefix and the difference array for any operation other than
+. - Use a dict of prefixes for subarray counting, seeded
{0: 1}for counts and{0: -1}for the longest. Comment why each seed has that form. - Respect the static-versus-updates limit: refuse an update on a structure declared static. When point updates are declared, choose between rebuilding the prefix and square-root blocks with a cost model, and name what production code would use.
Run six demo workloads, and show the refusals for a 2-D max declaration and an xor batch of range updates. Check every operation against a brute-force model, counting exceptions as failures, and then fuzz each structure on small random workloads. Time each demo against the brute force with best_of. State the complexity of every structure.
Stuck? Solve it with a mentor.
Your first 1-on-1 session is free.