Card 05/ 07

GotchaDifficulty: Intermediate2 min

Choosing a Pattern From a Keyword Instead of a Property

"Largest" suggests a heap, but the three largest values of a week are not three consecutive days: the property "consecutive" picks the window.

Choosing a pattern from a word in the question, rather than from a property the problem has, gives a fast answer to a different question. The trigger is a keyword that a pattern is known for: "largest" and "top" for a heap, "sorted" for binary search. It feels right because the word does belong to that pattern in most of the problems where it appears. A museum counts its visitors each day of a week, in hundreds: 9, 1, 1, 8, 7, 2 and 6 from Monday to Sunday, and wants the largest total over three consecutive days, to plan a three-day exhibition.

The first listing takes "largest" as the cue and keeps the three largest days in a heap; the second takes "consecutive" as the property and slides a window of three days.

The keyword's pattern and the property's pattern on the same week

visitors_keyword.pypy
import heapq

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
visitors = [9, 1, 1, 8, 7, 2, 6]

largest = heapq.nlargest(3, range(len(visitors)), key=visitors.__getitem__)
picked = sorted(largest)
print("best three days:", sum(visitors[d] for d in picked))
print("days used:", " ".join(days[d] for d in picked))
OutputRan with python:3.14.8-slim-trixie (Python 3.14.8)
best three days: 24
days used: Mon Thu Fri
visitors_property.pypy
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
visitors = [9, 1, 1, 8, 7, 2, 6]

window = sum(visitors[:3])
best, best_start = window, 0
for end in range(3, len(visitors)):
    window += visitors[end] - visitors[end - 3]
    if window > best:
        best, best_start = window, end - 2
print("best three days:", best)
print("days used:", " ".join(days[best_start:best_start + 3]))
OutputRan with python:3.14.8-slim-trixie (Python 3.14.8)
best three days: 17
days used: Thu Fri Sat

The heap answers 24, from Monday, Thursday and Friday, which are not consecutive, so no exhibition could run on them. The window answers 17, from Thursday to Saturday, the best three days in a row. Both programs run without error, which is why the mistake survives: the heap's answer is correct for the question it answered.

The check is to name the property the pattern needs and test the problem for it before choosing. A heap needs the items to be free to come from anywhere; this problem requires them to touch, which is the sliding window's property. The same mistake happens with "sorted": an array described as sorted suggests binary search, but counting the pairs below a target in a sorted array is a question about pairs, which two pointers answer in O(n), and a binary search per element only reaches O(n log n). Binary search needs a single point where a test turns from false to true, and the word "sorted" does not supply one.