Skip to content

Commit b2b4b9d

Browse files
authored
Merge pull request soapyigu#356 from soapyigu/Design
Add a solution to Search Suggestions System
2 parents 8630c43 + 67ee0da commit b2b4b9d

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Design/SearchSuggestionsSystem.swift

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/search-suggestions-system/
3+
* Primary idea: Use trie to add and search prefix (DFS).
4+
*
5+
* Time Complexity: O(n), Space Complexity: O(n)
6+
*
7+
*/
8+
9+
class SearchSuggestionsSystem {
10+
func suggestedProducts(_ products: [String], _ searchWord: String) -> [[String]] {
11+
let trie = Trie()
12+
var res = [[String]]()
13+
14+
products.forEach { trie.insert($0) }
15+
16+
return (1...searchWord.count).map { trie.searchWords(for: String(searchWord.prefix($0))) }
17+
}
18+
19+
private class Trie {
20+
let root = TrieNode()
21+
22+
func insert(_ word: String) {
23+
var node = root
24+
25+
for char in word {
26+
if node.charNodeMap[char] == nil {
27+
node.charNodeMap[char] = TrieNode()
28+
}
29+
30+
node = node.charNodeMap[char]!
31+
}
32+
33+
node.isWord = true
34+
}
35+
36+
func searchWords(for term: String) -> [String] {
37+
var res = [String](), node = root
38+
39+
for char in term {
40+
guard let next = node.charNodeMap[char] else {
41+
return res
42+
}
43+
44+
node = next
45+
}
46+
47+
dfs(&res, term, node)
48+
49+
return Array(res.sorted().prefix(3))
50+
}
51+
52+
private func dfs(_ res: inout [String], _ path: String, _ node: TrieNode) {
53+
if node.isWord {
54+
res.append(path)
55+
}
56+
57+
for (char, next) in node.charNodeMap {
58+
dfs(&res, path + String(char), next)
59+
}
60+
}
61+
}
62+
63+
private class TrieNode {
64+
var isWord: Bool
65+
var charNodeMap: [Character: TrieNode]
66+
67+
init() {
68+
isWord = false
69+
charNodeMap = [Character: TrieNode]()
70+
}
71+
}
72+
}

0 commit comments

Comments
 (0)