GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #1268 - Search Suggestions System - LeetCode JavaScript Solutions

Back to all solutions

#1268 - Search Suggestions System

Medium • View on LeetCode • View on GitHub
Array String Sorting Binary Search Heap Priority Queue Trie

Problem Description

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 minimums products.

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

Solution

/**
 * @param {string[]} products
 * @param {string} searchWord
 * @return {string[][]}
 */
var suggestedProducts = function(products, searchWord) {
  products.sort();
  const result = new Array(searchWord.length);
  for (let i = 0; i < searchWord.length; i++) {
    products = products.filter((word) => word[i] === searchWord[i]);
    result[i] = products.slice(0, 3);
  }
  return result;
};
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.