LeetCode: Search Suggestions System Solution
1/**2 * @param {string[]} products3 * @param {string} searchWord4 * @return {string[][]}5 */6var suggestedProducts = function (products, searchWord) {7 products.sort((productA, productB) => productA.localeCompare(productB))89 const prefixResults = new Map()10 products.forEach(product => {11 let term = ""12 for (const char of product) {13 term += char14 if (prefixResults.has(term) === false) {15 prefixResults.set(term, [])16 }1718 prefixResults.get(term).push(product)19 }20 })2122 const res = []23 let searchTerm = ""24 for (const char of searchWord) {25 searchTerm += char26 res.push((prefixResults.get(searchTerm) || []).slice(0, 3))27 }2829 return res30}
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
Jun 2, 2021