← Questions

Recent search history with a size limit

0

A coding interview question asked at Google and Microsoft. It tests design, lru cache and linked list.

Build the recent-searches list behind a search box. When the user focuses the box, it shows their most recent distinct searches, newest first. Every search the user runs is recorded. A term that is searched again moves to the top; it is never listed twice. The history holds at most capacity distinct terms; when a new term would exceed that, the term searched least recently is dropped.

Implement the SearchHistory class:

  • SearchHistory(capacity: int) creates an empty history. capacity is a positive integer.
  • add(term: str) -> None records a search for term.
  • get_top_k(k: int) -> list[str] returns up to k stored terms, most recent first. If fewer than k terms are stored, return all of them. k = 0 returns an empty list.

Terms are compared exactly (no case folding). Aim for O(1) per add and O(k) per get_top_k, with capacity up to 10^6 and up to 10^6 calls.

Example 1

h = SearchHistory(3)
h.add("llama")
h.add("tpu")
h.add("rlhf")
h.get_top_k(2)    # ["rlhf", "tpu"]
h.add("llama")    # already stored: moves to the front, nothing is dropped
h.get_top_k(3)    # ["llama", "rlhf", "tpu"]
h.add("moe")      # 4 distinct terms > capacity 3: "tpu" is dropped
h.get_top_k(10)   # ["moe", "llama", "rlhf"]

Example 2

h = SearchHistory(1)
h.add("a")
h.add("a")
h.add("b")
h.get_top_k(5)    # ["b"]

Clarifying questions

  • Is an empty string a valid term?
  • Can capacity change after construction?
  • Is get_top_k read-only, so it does not count as a use?
  • Must the history survive a restart or work across devices?

What a strong answer covers

  • Uses a hash map from term to node plus a doubly linked list ordered by recency (or an OrderedDict): add moves an existing term to the front or inserts a new one and drops the tail when over capacity, all O(1).
  • get_top_k walks min(k, size) nodes from the front: O(k).
  • Handles k = 0, capacity = 1, and repeated adds of the same term (example 2).
  • Tests example 1, where a re-added term moves to the front and nothing is dropped.

Follow-ups

  • Return suggestions that start with a typed prefix, most recent first.
  • Delete a single term from the history.
  • Rank by frequency and recency combined.

Where it's asked

What it tests

design · lru cache · linked list · hash map

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding