Score Every Search Query by How Many Queries Share Its Prefixes

Last updated: November 29, 2026

Quick Overview

Given a list of search queries, the score of a query is the sum, over each of its non-empty prefixes, of how many queries in the list start with that prefix. Return the score of every query.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Medium

0

0

0 solved


Given a list of search queries, the score of a query is the sum, over each of its non-empty prefixes, of how many queries in the list start with that prefix. Return the score of every query.

An online assessment style question in Amazon's style, framed around estimating how crowded a query's typeahead path is: a query whose prefixes are shared by many others is harder to surface early. It checks that you replace a quadratic prefix comparison with a counting trie.

What the Interviewer Expects
  • Sees the brute force is O(n^2 L) or worse
  • Builds a trie with a pass-through count per node
  • Computes each score by summing counts along its path
  • States O(total characters) time
  • Handles duplicate queries correctly
Key Topics to Cover
tries
counting
prefix search
strings
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you update scores incrementally when a new query is added?
  • How would you cap memory if the vocabulary is huge?
  • What if only prefixes of length at least 3 should count?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: up to around 10510^5 queries, total length up to around 10610^6. Output: one integer per query. Duplicates both count (two copies of tv each contribute to prefix t)....

High-Level Design

For each query and each prefix, counting matches against all queries is O(n2L)O(n^2 L). Notice that the count for prefix p is exactly the number of queries whose trie path passes through the node for `p...


Submit Your Answer
Markdown supported