Problem 473819 · medium · Level 04 Non-Linear Data Structures

Hints Under the Shop's Search Box

trie · DFS · sorting

An online shop shows hints under its search box. Its catalogue products holds distinct names, and a customer types search_word one letter at a time. After every letter the shop shows up to 3 product names that begin with everything typed so far: the alphabetically first ones, listed in alphabetical order. Return one list of hints for each letter typed.

Examples

Input:  products = ["pencil", "pen", "penguin", "pepper", "pear", "peach"], search_word = "pens"
Output: [["peach", "pear", "pen"], ["peach", "pear", "pen"], ["pen", "pencil", "penguin"], []]
Explanation: no product starts with "pens", so the last list is empty.

Input:  products = ["mug", "mint", "milk", "mile", "mitt", "milestone"], search_word = "mile"
Output: [["mile", "milestone", "milk"], ["mile", "milestone", "milk"], ["mile", "milestone", "milk"], ["mile", "milestone"]]

Constraints

  • 0 <= len(products) <= 5000, lowercase words of length <= 20
  • 1 <= len(search_word) <= 20
  • Once no product matches a prefix, every later suggestion list is empty
  • Target: build in O(total characters); each suggestion should stop exploring after three matches are found

Goals

  • Follow a trie one typed character at a time
  • Collect the lexicographically smallest completions with an ordered DFS
Starting Python…