Search Suggestions System - Problem

You are given an array of strings products and a string searchWord. Design a system that suggests at most three product names from products after each character of searchWord is typed.

Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix, return the three lexicographically minimum products.

Return a list of lists of the suggested products after each character of searchWord is typed.

Input & Output

Example 1 — Basic Case
$ Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]
💡 Note: Typing 'm': products with 'm' are ["mobile","moneypot","monitor"]. Typing 'mo': products with 'mo' are ["mouse","mousepad"]. For 'mou', 'mous', 'mouse': all return ["mouse","mousepad"].
Example 2 — No Matches
$ Input: products = ["havana"], searchWord = "havana"
Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
💡 Note: Each character of 'havana' matches the product 'havana', so we return ['havana'] for each prefix.
Example 3 — Empty Results
$ Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
💡 Note: Typing 'b': ['baggage','bags','banner']. 'ba': ['baggage','bags','banner']. 'bag': ['baggage','bags']. 'bags': ['bags'].

Constraints

  • 1 ≤ products.length ≤ 1000
  • 1 ≤ products[i].length ≤ 3000
  • 1 ≤ searchWord.length ≤ 1000
  • products[i] and searchWord consist of lowercase English letters only

Visualization

Tap to expand
Search Suggestions SystemProducts: ["mobile", "mouse", "moneypot", "monitor", "mousepad"]SearchWord: "mouse"Type: "m"Suggestions:mobile, moneypot, monitorType: "mo"Suggestions:mouse, mousepadType: "mou"Suggestions:mouse, mousepadAs we type more characters, suggestions become more specificFinal Output: [["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]Challenge: Return at most 3 lexicographically smallest matches for each prefixSolution: Sort products first, then use efficient prefix matching
Understanding the Visualization
1
Input Data
Products array and search word to type
2
Progressive Filtering
Each typed character narrows down suggestions
3
Output
List of suggestions for each prefix
Key Takeaway
🎯 Key Insight: Sorting products first enables efficient prefix matching and guarantees lexicographical order
Asked in
Amazon 85 Microsoft 45 Google 30 Apple 25
127.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen