LeetCode: Prefix And Suffix Search Solution
1/**2 * @param {string[]} words3 */4var WordFilter = function (words) {5 this.mapPrefix = new Map()6 this.mapSuffix = new Map()78 for (const [wordIndex, word] of words.entries()) {9 for (let i = 0; i <= word.length; i++) {10 const [prefix, suffix] = [11 word.substring(0, i),12 word.substring(word.length - i),13 ]1415 if (!this.mapPrefix.has(prefix)) {16 this.mapPrefix.set(prefix, [])17 }18 if (!this.mapSuffix.has(suffix)) {19 this.mapSuffix.set(suffix, [])20 }2122 this.mapPrefix.get(prefix).push(wordIndex)23 this.mapSuffix.get(suffix).push(wordIndex)24 }25 }26}2728/**29 * @param {string} prefix30 * @param {string} suffix31 * @return {number}32 */33WordFilter.prototype.f = function (prefix, suffix) {34 if (!this.mapPrefix.has(prefix) || !this.mapSuffix.has(suffix)) {35 return -136 }3738 const [prefixes, suffixes] = [39 this.mapPrefix.get(prefix),40 this.mapSuffix.get(suffix),41 ]42 let [i, j] = [prefixes.length - 1, suffixes.length - 1]4344 while (i >= 0 && j >= 0) {45 if (prefixes[i] < suffixes[j]) {46 j--47 } else if (prefixes[i] > suffixes[j]) {48 i--49 } else {50 return prefixes[i]51 }52 }5354 return -155}
Comments
Loading comments...
Tags
leetcode
trie
hashmap
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: Non Decreasing Array
May 5, 2021
Previous Post
LeetCode: Powerful Integers
May 1, 2021