Search Suggestions System

Implement suggestedProducts

Given a list of products and a searchWord being typed one character at a time, return a list of suggestion lists — one per character typed — where each entry holds up to 3 lexicographically smallest products that still have the typed-so-far prefix. Sorting the products once turns "find every product with this prefix" into a contiguous block that a binary search can locate directly. Going further, inserting the sorted products into a trie — and letting each node cache the first 3 products that ever pass through it — turns every later query into a plain O(1)-per-character walk with no searching left to do at all: the trie already did the sorting and filtering work once, up front.

Example 1:

Input: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"

Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]

Example 2:

Input: products = ["havana"], searchWord = "havana"

Output: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]

Example 3:

Input: products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"

Output: [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]

+ 7 hidden test cases run on Submit.

Constraints:

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

products =

["mobile", "mouse", "moneypot", "monitor", "mousepad"]

searchWord =

mouse