MrainW's Home

All things come to those who wait!

0%

LeetCode 208. Implement Trie (Prefix Tree)

Question

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

https://leetcode.com/problems/implement-trie-prefix-tree/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}

public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c-'a']==null) node.children[c-'a'] = new TrieNode();
node = node.children[c - 'a'];
}
node.isWord = true;
}

public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a']==null) return false;
node = node.children[c-'a'];
}
return node.isWord;
}

public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c: prefix.toCharArray()){
if(node.children[c-'a']==null) return false;
node = node.children[c-'a'];
}
return true;
}

class TrieNode {
TrieNode[] children;
boolean isWord;
public TrieNode(){
children = new TrieNode[26];
}
}
}

Complexity:

Time complexity: O( n)

Space complexity: O(1)

Welcome to my other publishing channels