Advertisement
jorupp

https://leetcode.com/problems/search-suggestions-system

Jul 18th, 2023
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. type TrieNode = {
  2. word?: string;
  3. } & {
  4. [letter: string]: TrieNode | boolean;
  5. }
  6.  
  7. const targetWords = 3;
  8.  
  9. function suggestedProducts(products: string[], searchWord: string): string[][] {
  10. const root: TrieNode = { isWord: false };
  11. for(const product of products) {
  12. let node = root;
  13. for(const ch of product) {
  14. if (!node[ch]) {
  15. node[ch] = { };
  16. }
  17. node = node[ch] as TrieNode;
  18. }
  19. node.word = product;
  20. }
  21. function fillWords(node: TrieNode, words: string[]) {
  22. if (!node) return;
  23. if (node.word) {
  24. words.push(node.word);
  25. }
  26. // TODO: we could probably save some time by pre-sorting these
  27. for(const ix of Object.keys(node).sort()) {
  28. if (words.length >= targetWords) break;
  29. if (ix.length === 1) {
  30. fillWords(node[ix] as TrieNode, words);
  31. }
  32. }
  33. }
  34.  
  35. const results: string[][] = [];
  36. {
  37. let node = root;
  38. for (const ch of searchWord) {
  39. const result: string[] = [];
  40. if (node) {
  41. node = node[ch] as TrieNode;
  42. fillWords(node, result);
  43. }
  44. results.push(result);
  45. }
  46. }
  47.  
  48. return results;
  49. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement