Choosing a Data Structure
Most speed decisions in puzzles aren't about clever tricks but about which data structure you use for the question asked most often. Ask yourself: which operation runs over and over?
| Question asked often | Structure | Cost per question |
|---|---|---|
| "is x there?" | a set (map[T]struct{}) | O(1) |
| "how many times does x appear?" | map[T]int | O(1) |
| "what's element i?" | a slice | O(1) |
| "sum from i to j?" | a prefix sum | O(1) after one O(n) pass |
| "is x there?" in a slice | a loop | O(n) |
| "what's the smallest value now?" | a slice sorted again | O(n log n) every time |
The last row is a sign that a better structure exists, such as a heap, which comes in a later chapter.
Build once, ask many times
The pattern is nearly always the same: read the input, turn it into the right structure once, then answer every question from that structure. Checking q IDs against a slice of n visits takes n × q steps. Building a set takes n steps, then every check is constant: n + q in total.
A set gives you a bonus too: len(set) answers "how many different ones?" straight away.
Task
A library logs a visitor's card number every time someone comes in. The input has one visitors line with every visit (a card can come many times), then several check <number> lines.
For every check line, in order, print:
<number> yes
if that card has visited, or <number> no if it hasn't. At the end, print:
distinct visitors: <number of different cards>
Build a set once from the visits, then answer every check from it. The output must match the expected output exactly.