Problem set 2: two pointers, windows and prefix sums
🌍 In real life. A shopkeeper in Chawkbazar keeps a daily sales list. One day he wants to know whether a slogan on a banner reads the same backwards; another day, which 7 days in a row sold the most; and every evening his accountant asks for the total of some stretch of days. Three jobs over a row of items, each with a quick pattern.
The idea in one sentence: when the items sit in a row, two pointers walk in from the ends, a window slides along keeping a running total, and a prefix sum list answers any range total by one subtraction.
Its words:
- window: a run of k items next to each other, kept with a running total
- prefix sum: the running total up to each position, so any range total is one subtraction
- clean first: tidy the input (lower-case it, drop what doesn't count) before you compare
This set (Easy to Medium)
- Slogan palindrome. Does a sentence read the same backwards if you ignore spaces, punctuation and capital letters?
- Best 7-day stretch. The biggest total of k days in a row.
- Accountant's ranges. For many questions (l, r), the total from day l to day r.
How to work a problem:
- spot the row: items next to each other, with an order that matters
- ends moving inwards → two pointers; a fixed-length stretch → a sliding window; many range questions → prefix sums
- try the smallest inputs: empty, one item, k equal to the length
A fixed window slides one place at a time: one number comes in on the right and one leaves on the left:
Why these patterns fit. A palindrome compares the first letter with the last, then moves both inwards: two pointers do exactly that, skipping what isn't a letter or digit. A window's next total differs from the last by one number in and one out, so there is no need to add the whole window again. A prefix list stores every running total once, and the total from l to r is prefix[r + 1] − prefix[l].
What it costs, by counting. For 1,000,000 days and k = 7, the window does about 1,000,000 additions, O(n), where adding each window afresh would take 7,000,000. For 100,000 days and 100,000 questions, prefix sums take 100,000 steps to build and one subtraction per question, O(n + q), instead of up to 10,000,000,000 additions.
A warm-up in the same style, counting the vowels in each sliding window of 3 letters:
def vowels_per_window(word, k):
is_vowel = [ch in "aeiou" for ch in word]
count = sum(is_vowel[:k])
counts = [count]
for i in range(k, len(word)):
count += is_vowel[i] - is_vowel[i - k] # True counts as 1, False as 0
counts.append(count)
return counts
print(vowels_per_window("education", 3))Mistakes and edge cases.
- comparing the raw string:
s == s[::-1]fails as soon as there is a space or a capital letter - off by one in a range: the total from l to r includes r, so it is
prefix[r + 1] − prefix[l] - picking the k largest numbers: a window must be k numbers next to each other
- negative numbers: a window total can be negative; start
bestfrom the first window, not from 0
Quiz
"For 50,000 questions, give the total sales from day l to day r." Which pattern?
- Prefix sums
- Sorting the sales
- Backtracking
What does this print?
def max_window_sum(nums, k): total = sum(nums[:k]) # the first window best = total for i in range(k, len(nums)): total += nums[i] - nums[i - k] # slide: one number in, one out best = max(best, total) return best print(max_window_sum([3, -1, 4, -1, 5], 2))What does this print?
def range_sums(nums, queries): prefix = [0] for x in nums: prefix.append(prefix[-1] + x) # prefix[i] = sum of nums[:i] return [prefix[r + 1] - prefix[l] for l, r in queries] print(range_sums([3, 1, 4, 1, 5], [(0, 2), (4, 4)]))Why doesn't s == s[::-1] check "Madam, I'm Adam"?
- Spaces, punctuation and capital letters break the comparison
- It is too slow
- Strings can't be reversed
vowels_per_window("education", 3) should be [2, 1, 2, 1, 2, 2, 2], but the last count comes out 1. Which line is wrong?
def vowels_per_window(word, k): is_vowel = [ch in "aeiou" for ch in word] count = sum(is_vowel[:k]) counts = [count] for i in range(k, len(word)): count += is_vowel[i] - is_vowel[i - 1] counts.append(count) return counts
Coding tasks
Slogan palindrome. Write
is_palindrome_sentence(s):Trueifsreads the same backwards when only letters and digits count and capital letters are treated as small ones.Best stretch of days. Write
max_window_sum(nums, k): the biggest total ofknumbers next to each other innums(1 ≤ k ≤ len(nums)).Accountant's ranges. Write
range_sums(nums, queries): for each(l, r)inqueries, the total ofnums[l]tonums[r], both included. Return the answers as a list.