Skip to content

Latest commit

 

History

History
24 lines (20 loc) · 1.19 KB

File metadata and controls

24 lines (20 loc) · 1.19 KB

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.

Screen Shot 2021-11-11 at 00 50 10

Screen Shot 2021-11-11 at 00 50 23

/**
 * @param {string[]} products
 * @param {string} searchWord
 * @return {string[][]}
 */
var suggestedProducts = function(products, searchWord) {
    let sorted = products.sort();
    let stack = [];
    
    for(let i = 0; i < searchWord.length; i++) {
        sorted = sorted.filter(product => product[i] === searchWord[i]);
        stack.push(sorted.slice(0, 3));
    }
    return stack;
};