Recent search history with a size limit
I was asked this
No reports yet. Sign in to say where you were asked it.
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.capacityis a positive integer. -
add(term: str) -> Nonerecords a search forterm. -
get_top_k(k: int) -> list[str]returns up tokstored terms, most recent first. If fewer thankterms are stored, return all of them.k = 0returns 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
capacitychange after construction? - Is
get_top_kread-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):addmoves an existing term to the front or inserts a new one and drops the tail when over capacity, allO(1). -
get_top_kwalksmin(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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.

