LeetCode: Search Suggestions System Solution

1/**
2 * @param {string[]} products
3 * @param {string} searchWord
4 * @return {string[][]}
5 */
6var suggestedProducts = function (products, searchWord) {
7 products.sort((productA, productB) => productA.localeCompare(productB))
8
9 const prefixResults = new Map()
10 products.forEach(product => {
11 let term = ""
12 for (const char of product) {
13 term += char
14 if (prefixResults.has(term) === false) {
15 prefixResults.set(term, [])
16 }
17
18 prefixResults.get(term).push(product)
19 }
20 })
21
22 const res = []
23 let searchTerm = ""
24 for (const char of searchWord) {
25 searchTerm += char
26 res.push((prefixResults.get(searchTerm) || []).slice(0, 3))
27 }
28
29 return res
30}

Comments

Loading comments...

Tags

leetcode

string

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Max Area Of Island

HoningJS

Search Posts