Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 18: Strings, Sliding Windows and Prefix Sums

Strings and arrays appear in a large share of contest problems, and two techniques dominate them. The first is the sliding window: a window of consecutive items that moves across the data, usually expanding on the right and shrinking on the left. It solves problems like "the longest substring with no repeating character" or "the shortest subarray summing to at least K" in a single O(n) pass, where the naive approach would check every possible window — O(n^2) of them. The trick is that the window only moves forward: each item enters once and leaves once.

The example below finds the longest substring without a repeated character. The window is the current substring; a dictionary records the last position of each character. When a repeated character appears inside the window, the left edge jumps past its previous occurrence. The answer is the widest the window ever gets. The same skeleton — expand right, shrink left while a condition is violated, track the best window — solves a whole family of problems, and recognising the family is the skill.

def longest_unique(s):
    last_seen = {}
    left = 0
    best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best


print(longest_unique("abcabcbb"))  # 3 — "abc"
print(longest_unique("bbbbb"))     # 1 — "b"
print(longest_unique("pwwkew"))    # 3 — "wke"

Prefix sums: answering range questions instantly

The second technique is the prefix sum: an array where each entry holds the sum of everything up to that point. Once you have built it — one O(n) pass — the sum of any range is a single subtraction: sum(i..j) = prefix[j+1] - prefix[i]. A problem that asks for the sums of a thousand ranges goes from a thousand scans to a thousand subtractions. Prefix sums also turn "find a subarray summing to K" into a dictionary problem: as you scan, you check whether the current prefix minus K has been seen before, which is the same complement idea as two-sum from the last lesson.

Both techniques share a deeper lesson: many contest problems are about avoiding repeated work. The naive solution recomputes something for every pair or every window; the good solution finds a way to reuse the previous computation. Sliding windows reuse the window; prefix sums reuse the running total; memoisation reuses subproblem answers. When you are stuck on a problem, ask what you are computing twice — and what structure would let you compute it once.

Going further

Sliding windows come in two kinds. A variable window, like the one in this lesson, grows and shrinks as needed to satisfy a condition. A fixed window is always the same size — for example, the maximum sum of any three consecutive numbers — and it slides by adding the new item and subtracting the one that falls out, which is really a prefix-sum idea in disguise. Knowing which kind a problem needs is half the battle: "longest" or "shortest" usually means a variable window, while "any k consecutive" means a fixed one.

The two-pointer idea also solves the classic palindrome check in a single pass: put one pointer at each end of the string and move them inward, comparing as you go. If any pair differs, the string is not a palindrome. The same inward scan, with a small twist, finds the longest palindromic substring by expanding outward from each possible centre. Strings reward this kind of thinking — pointers moving, windows sliding, prefixes accumulating — because a string is just an array of characters, and every array technique applies to it.

Prefix sums have a neat extension: the two-dimensional prefix sum, which answers the sum of any rectangle in a grid in constant time. Build a table where each entry holds the sum of the rectangle from the top-left corner to that cell, then the sum of any rectangle is a combination of four table lookups — add two corners, subtract two others. It is the same idea as the one-dimensional version, applied twice, and it appears in image processing and in grid problems where many rectangle queries must be answered quickly. The pattern is worth knowing because it shows how a good idea scales to a new dimension.

Key Terms

Sliding window
A window of consecutive items that moves across data, expanding right and shrinking left, in one O(n) pass.
Substring
A consecutive run of characters within a string.
Subarray
A consecutive run of items within a list.
Prefix sum
An array where entry i holds the sum of the first i items, so any range sum is one subtraction.
Range sum query
Asking for the sum of items between two positions; answered in O(1) with a prefix sum.
Complement (prefix)
In the subarray-sum problem, the earlier prefix value (current prefix minus K) whose presence proves a match.
Two-sum pattern
Checking for a needed complement in a dictionary while scanning once — reused for prefix sums.

Discussion Questions

  1. Why does the sliding window only move forward? What would go wrong if the left edge ever moved backwards?
  2. How is the prefix-sum trick the same idea as the two-sum dictionary from the last lesson? What plays the role of the complement?
  3. When does a sliding window not work? What property must the problem have for the window to be valid?

Practice Questions

  1. Trace longest_unique("abcabcbb"). What is the window when the answer 3 is first reached?
  2. Why is the sliding window O(n) even though it has a loop with a moving left edge?
  3. Given prefix sums [0, 3, 8, 10], what is the sum of items 1 to 2 (0-indexed)?
  4. How would you find a subarray summing to K using prefix sums and a dictionary?
  5. Why is building the prefix sum array itself O(n)?
Show answers
  1. The window "abc" (positions 0–2). When the second 'a' arrives at position 3, the left edge jumps to 1, and the window never grows wider than 3.
  2. Each character enters and leaves the window at most once. The right edge moves n times and the left edge moves at most n times, so the total work is O(n).
  3. 7. prefix[3] - prefix[1] = 10 - 3 = 7, which is the sum of the items at positions 1 and 2.
  4. Scan, keeping a running prefix; check whether prefix - K was seen before. If it was, the items between that earlier position and now sum to K.
  5. Each entry is the previous entry plus one new item. One pass fills the whole array.
Keep reading to complete this lesson