The task: an online store’s search box receives a stream of queries. Show the ten most searched terms of the last hour, refreshed every minute. We will solve it in three rounds, each fixing a weakness of the previous one.

Round one: counts, then pick the biggest

Keep a hash map from term to count. Every incoming query adds one. To read the top k, you could sort all entries by count and take the first k. With 5 million distinct terms that is a full sort, O(n log n), to answer a question that needs only ten entries. Wasteful.

The better tool is a min-heap of size k. A min-heap always exposes its smallest element at the top, and inserting or removing costs O(log k). Here is a miniature with k = 3 and six terms already counted:

TermCount
saree50
kurta42
mobile90
shoes31
watch60
bag45
  1. Read saree (50), kurta (42), mobile (90). The heap is not full-sized beyond 3, so push all three. Smallest at the top: kurta, 42.
  2. Read shoes (31). It is smaller than the top (42), so it cannot be in the best three. Ignore it.
  3. Read watch (60). Larger than 42. Remove kurta, push watch. Heap holds 50, 60, 90; smallest is now saree, 50.
  4. Read bag (45). Smaller than 50. Ignore.

Result: mobile, watch, saree. The cost is n comparisons against the top, plus O(log k) only when something gets in. For k = 10, log k is about 3, so the whole pass is close to O(n), with memory for just ten extra entries. Python’s heapq.nlargest and Java’s PriorityQueue do this. The counter itself, the hash map, still holds every distinct term, which becomes the next problem.

Round two: “last hour” means old queries must expire

A plain counter counts forever. We need a sliding window. Storing every query with a timestamp and rescanning is expensive, so approximate the window with buckets: one hash map per minute, 60 of them, arranged in a ring. A new query increments the current minute’s map. Each minute, the oldest bucket is dropped and a fresh one begins.

To avoid summing 60 maps for every term at each refresh, keep a running total map as well. When a bucket expires, subtract its counts from the totals (and remove terms that reach zero). Then the heap pass runs over the totals. The window edge is blurry by up to one minute, which for a “trending searches” widget is entirely fine. If you need exactness, use smaller buckets and pay more memory.

Be careful about whose clock decides which bucket a query belongs to. Using event time, when the user searched, handles delays better than using the arrival time at your server, but then you must decide how late an event may arrive before you drop it.

Round three: one machine is not enough

At high volume the stream arrives at many servers. A tempting shortcut: each server computes its own top ten, and a central service merges these lists. Watch what goes wrong. Suppose “diwali lamps” is the 11th most popular term on each of three servers, with 40 searches each, so 120 across the system. Every server drops it from its local list, so it never reaches the merge, though its global count of 120 may beat terms that were in the lists. Local top-k lists do not combine into the global top-k.

Two sound options. One: route by term. Hash the term so that every occurrence of “diwali lamps” lands on the same worker. Each worker then holds exact counts for its own terms, computes its local top k, and merging is correct, because any global top-k term is in the top-k of the one shard that owns it. Two: ship the full per-bucket counts to an aggregation tier. Option one scales better. Its risk is a hot shard if one term dominates, which a good combiner step before routing softens.

When even the counter is too big

With billions of distinct strings (long-tail queries, typos), exact counting in memory is impractical. If approximate is acceptable, use a sketch.

  • Count-Min Sketch. A small grid of counters with several rows, each row using a different hash function. Incrementing a term bumps one counter per row. To estimate a count, take the minimum across the rows. Collisions can only inflate counters, so the estimate never undercounts, and it overcounts by a bounded amount you control by choosing grid size. Pair it with a small heap of current candidates so you can still list the actual terms.
  • Space-Saving or Misra-Gries. These keep only a fixed number of counters, evicting the smallest when a new term arrives. They guarantee that any term above a chosen frequency share is retained.

The trade is stated plainly: you swap exact answers for bounded error and a fixed, small memory budget. For a trending widget, being off by a few counts among terms with thousands of searches changes nothing a shopper can see. For billing, it would be unacceptable.

What carried through all three rounds

The heap stayed small throughout; only the counting changed with scale. When a question asks for “top k” or “k largest”, ask yourself first what must be remembered, and whether the answer needs to be exact. The two decisions separate the hash map solution, the bucketed one and the sketch.

Figures and names in the examples are illustrative.

Leave a Reply

Trending