Skip to content
Advertisement

Search Suggestions System

Below is the problem statement and below it , is my solution using TrieNode Data structure but My ans is wrong and i am not able to understand where my code gone wrong , please help ……

Given an array of strings products and a string searchWord. We want to 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 the searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.

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

Example 1:

JavaScript

Explanation: products sorted lexicographically = [“mobile”,”moneypot”,”monitor”,”mouse”,”mousepad”] After typing m and mo all products match and we show user [“mobile”,”moneypot”,”monitor”] After typing mou, mous and mouse the system suggests [“mouse”,”mousepad”]

JavaScript

Advertisement

Answer

If I had to guess, other than the solution’s performance, the functional problem might be this:

JavaScript

The addToList function adds all terminals under a node to a list. You’re calling it with root, but you probably mean to call it with root.child[index].

Consider the input “mou”. root will be the node representing prefix mo, the string will be "u". You will return a list containing “mobile”, which does not match the “mou” input.


As for performance, just sort the list, do a binary search for the prefix and return the next three indexes if their prefixes match. No trie needed (though a trie as an index into a sorted array would be even better performance), and no song-and-dance is needed to sort lists only to discard all but three values.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement