Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active June 29, 2021 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/05526bd70407d1d60def334de4c45b3d to your computer and use it in GitHub Desktop.
Save krzyzanowskim/05526bd70407d1d60def334de4c45b3d to your computer and use it in GitHub Desktop.
Trie autocomplete
import Foundation
/*
D
O
O
G R
S
look for prefix, then DFS children for option
*/
import Foundation
/*
D
O
O
G R
S
look for prefix, then DFS children for option
*/
class Trie {
class Node {
var children: [Character: Node]
var isWord: Bool
init(isWord: Bool = false) {
children = [:]
self.isWord = isWord
}
}
private let root: Node
// build a trie
init(_ words: [String]) {
root = Node()
for word in words {
var current = root
for character in word {
if let child = current.children[character] {
// existing node
current = child
} else {
// new node
let n = Node()
current.children[character] = n
current = n
}
}
// that's the whole word node
current.isWord = true
}
}
func autocomplete(_ prefix: String) -> [String] {
var current = root
// traverse over the prefix word
for character in prefix {
if let child = current.children[character] {
current = child
} else {
return []
}
}
// then add "combinations" by traversing with dfs
return dfs(current, prefix)
}
private func dfs(_ node: Node, _ prefix: String) -> [String] {
var words: [String] = []
if node.isWord {
words += [prefix]
}
for (character, child) in node.children {
words += dfs(child, prefix + String(character))
}
return words
}
}
let t = Trie(["dog","dark","cat","door","dodge"])
let list = t.autocomplete("do")
print(list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment