1268. Search Suggestions System - Detailed Explanation

Problem statement

Given an array of strings called products and a string searchWord, design a system that suggests at most three product names from products after each character of searchWord is typed. The suggested products should have a common prefix with searchWord. If there are more than three products with a common prefix, return the three lexicographically smallest products.

For each character typed, that is for each prefix of searchWord, return a list of up to three suggestions.

Examples:

  • Example 1:

    • Input:
      products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"] searchWord = "mouse"
    • Output:
      [ ["mobile", "moneypot", "monitor"], ["mobile", "moneypot", "monitor"], ["mouse", "mousepad"], ["mouse", "mousepad"], ["mouse", "mousepad"] ]
    • Explanation: After typing:
      • "m": all products starting with "m" are considered. The three lexicographically smallest are returned.
      • "mo": similar to "m".
      • "mou": only "mouse" and "mousepad" start with "mou".
      • "mous" and "mouse": suggestions remain the same as in "mou".
  • Example 2:

    • Input:
      products = ["havana"] searchWord = "havana"
    • Output:
      [["havana"], ["havana"], ["havana"], ["havana"], ["havana"], ["havana"]]
    • Explanation: Since there is only one product, it is returned for every prefix.
  • Example 3:

    • Input:
      products = ["bags","baggage","banner","box","cloths"] searchWord = "bags"
    • Output:
      [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
    • Explanation: Each prefix of "bags" produces a list of matching products up to three suggestions.

Constraints:

  • The length of products and each product string can vary.
  • searchWord is a non-empty string.
  • All strings consist of lowercase English letters.
  • If no product has a prefix matching the current prefix of searchWord, return an empty list for that step.

This question belongs to the trie pattern. A trie, also called a prefix tree, stores one node per character, so every word that shares a prefix shares a path from the root. A sorted array with binary search answers the same query, and both solutions appear below. Design Gurus teaches the problem in the Search Suggestions System lesson of Grokking the Coding Interview.

Hints for the solution

  • Hint 1: Notice that suggestions must be sorted lexicographically. Sorting the products array first can simplify the process of selecting the smallest suggestions.

  • Hint 2: For each prefix of searchWord, you need an efficient way to find products starting with that prefix. Think about binary search on the sorted array to quickly locate the starting index of products matching the prefix.

Approaches to solve the problem

1. Brute force approach

Idea: For each prefix of searchWord, loop through the entire products array, check whether each product starts with the prefix, then sort the filtered list and pick up to three items.

Steps:

  • For every prefix of searchWord, iterate through each product.
  • Check whether the product starts with the prefix.
  • Sort the valid products lexicographically.
  • Choose the first three suggestions.

Downside:

  • This approach can be inefficient when products is large, because each prefix requires scanning all products.

Idea:

  1. Sort the products: Sorting the products lexicographically ensures that the suggestions come out in order.
  2. For each prefix: Use binary search to find the first product that starts with the current prefix.
  3. Collect suggestions: From the found index, check up to three products to see whether they start with the prefix, then add them to the suggestion list.

Steps:

  • Step 1: Sort the products array.
  • Step 2: For every character in searchWord, build the prefix incrementally.
  • Step 3: Use binary search, or a similar method, to locate the insertion point for the prefix in the sorted array.
  • Step 4: Check the next three products, where available, to see whether they share the prefix, and add them to the result.

Benefits:

  • The binary search reduces the search time per prefix to O(log n).
  • The overall approach is efficient. Most of the work happens during the initial sort, and each prefix then needs only a simple lookup.

3. Trie-based approach (alternative variation)

Idea: Build a trie from the products array. At each node of the trie, keep a list of up to three lexicographically smallest words that pass through that node. Then, for each prefix of searchWord, walk the trie to the node for that prefix and read its stored suggestions directly.

The node structure itself is the subject of Implement Trie (Prefix Tree), which is worth solving first.

Note:

  • The trie solution can be efficient for many queries over the same products, but it takes more code to implement.
  • The sorting and binary search method is often preferred for its simplicity.

Code implementations

Python code implementation

Python3
Python3

. . . .

Java code implementation

Java
Java

. . . .

Complexity analysis

  • Time complexity:

    • Sorting: Sorting the products array takes O(n log n) time, where n is the number of products.

    • Binary search: There are m prefixes, where m is the length of searchWord, and each one costs a binary search of O(log n) time.

    • Overall: The overall time complexity is O(n log n + m log n).

  • Space complexity:

    • The extra space holds the result list and the current prefix, which is O(m), plus the sorting space, which is typically O(n). Overall, space complexity is O(n + m).

Common pitfalls and edge cases

Common pitfalls

  • Not sorting: Failing to sort products first may produce the wrong lexicographical order for the suggestions.

  • Binary search edge cases: Some library searches return a negative value when the prefix is absent, and that value encodes the insertion point. Convert it before you use it as an index.

  • Prefix matching: While you iterate through the next few products, verify that each one really starts with the current prefix.

Edge cases

  • No matching products: If no product matches a given prefix, the suggestions list for that prefix should be empty.

  • Single product: When products contains only one element, confirm that it is returned for every matching prefix.

  • Identical prefixes: When many products share the same prefix, return at most three suggestions.

Alternative variations

  • Trie implementation: Build a trie from products and store the suggestions at each node. This method helps most when many queries hit the same set of products.

  • Dynamic updates: If products are added or removed often, consider data structures that support updates while preserving lexicographical order.

  • Autocomplete systems: Designing systems that suggest search queries or terms as a user types.

  • Prefix search: Finding all words in a dictionary that start with a given prefix.

  • Word ladder: Transform one word into another by changing a single letter at a time, using only valid intermediate words.

  • Design search autocomplete system: A harder variant that also ranks the suggestions by popularity.

The trie and the sorted-array search both appear in many other questions, so learning them by name is worthwhile. The recurring LeetCode patterns post lists the rest of the set, and Grokking the Coding Interview teaches each one with practice problems.

TAGS
Coding Interview Questions
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
What is floor division?
What is the highest salary in ServiceNow?
What is NeetCode?
What is the code tool for interview?
What is aptitude in coding?
What is the base salary for Stripe software engineer?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
Discounted price for Your Region

$99

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
About Us
Our Team
Careers
Partners
Contact Us
Become Affiliate
Copyright © 2026 Design Gurus, LLC. All rights reserved.