← Questions

Autocomplete with top-k suggestions

0
AmazonCodingLast asked Sep 2025

A coding interview question asked in Amazon's coding round, last asked Sep 2025. It tests trie, heap and strings.

Build an autocomplete. Given a history of past queries with their counts, return the k most popular queries that start with the prefix the user has typed. It must answer in real time, and counts change as users enter queries.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • Autocomplete(history: list[tuple[str, int]], k: int)
  • suggest(prefix: str) -> list[str] — up to k queries starting with prefix, by count descending, ties alphabetical. Matching is case-insensitive.
  • record(query: str) -> None — the user entered query; add 1 to its count, or add it with count 1.

Example

a = Autocomplete([("apple", 5), ("app store", 8), ("apply", 5), ("banana", 2)], k=2)
a.suggest("app")      ->  ["app store", "apple"]   # apple and apply tie at 5; apple first
a.record("apply")
a.suggest("app")      ->  ["app store", "apply"]   # apply now 6
a.suggest("ban")      ->  ["banana"]
a.suggest("x")        ->  []

Constraints

  • Up to 10^6 distinct queries of up to 100 characters; k at most about 10.
  • Many more suggest calls than record calls.

Clarifying questions

  • How are ties broken?
  • Case-insensitive matching? What about accents and non-Latin scripts?
  • How large is k, and is it fixed?
  • Must recorded queries show up immediately?

What a strong answer covers

  • A trie keyed by the normalised query; each node can store its top k completions so suggest is O(length of prefix + k), at the cost of updating up to L nodes per record and O(N · L · k) memory.
  • The alternative: store only counts at terminal nodes and search the subtree per request (cheap updates, slow queries for short prefixes), and when each is the right choice.
  • Updating stored top-k lists when a count rises: re-insert the query at each node on its path, keeping lists sorted.
  • Normalisation (lower case, Unicode normalisation) applied the same way to the index and the prefix.
  • Deletion, memory for a large history (a compressed trie, sharding by first letters), and batching streamed updates.

Follow-ups

  • Remove a query, for example one that is offensive.
  • Recent queries should count more than old ones.
  • Tolerate one typo in the prefix.

Where it's asked

  • Amazon · Coding · Last asked Sep 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

trie · heap · strings

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