21/32
Part 5 of 6 · The worked exampleLearn and do

A worked example: the shortest stretch that covers every page

The prompt: a site's request log lists the page each request hit. Find the shortest stretch of consecutive requests that includes every page that appears in the log at least once. Return (start, length).

Clarify first. Say it out loud: every page means every page in this log. If several stretches tie, return the first. An empty log returns (0, 0), and a log with one page returns (0, 1).

Give the obvious answer. From every start, extend until the stretch covers every page, and keep the shortest. That's O(n²) when the answer is long, and the measurements below show it. Say it and give its cost, then improve it.

Covering every page stays true as the window grows, so shrink while it does

This window has the opposite shape. Before, a window that broke the rule stayed broken as it grew. So you shrank while it was broken, and recorded the longest.

Here, a window that covers every page still covers them all as it grows. So shrink while it's still valid, and record the shortest.

As right moves forward, the best left for it never moves back. So left only moves forward again: two indexes, O(n). The state is a Counter of the pages in the window. The window covers everything when len(counts) equals the number of different pages.

from collections import Counter

def shortest_covering_run(log):
    need = len(set(log))
    counts = Counter()
    left = 0
    best_start, best_len = 0, 0
    for right, page in enumerate(log):
        counts[page] += 1
        # covers every page: record it, then try shorter
        while len(counts) == need:
            if best_len == 0 or right - left + 1 < best_len:
                best_start, best_len = left, right - left + 1
            counts[log[left]] -= 1
            if counts[log[left]] == 0:
                del counts[log[left]]
            left += 1
    return best_start, best_len

log = ["home", "search", "home", "cart", "search", "home", "pay", "cart", "search"]
print(shortest_covering_run(log))
Predict

The log is home, search, home, cart, search, home, pay, cart, search. What's the shortest stretch that holds all 4 pages?

Pick one to see what it prints.
Pick an answer above to see the rest