Skip to content

Commit 5dcf6c0

Browse files
authored
Enhance Trie data structure with added methods and tests (#5538)
1 parent 6868bf8 commit 5dcf6c0

File tree

3 files changed

+129
-51
lines changed

3 files changed

+129
-51
lines changed

DIRECTORY.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@
207207
* [SplayTree](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java)
208208
* [Treap](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/Treap.java)
209209
* [TreeRandomNode](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java)
210-
* [TrieImp](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/TrieImp.java)
210+
* [Trie](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/Trie.java)
211211
* [VerticalOrderTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java)
212212
* [ZigzagTraversal](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java)
213213
* devutils
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,28 @@
11
package com.thealgorithms.datastructures.trees;
22

3+
import java.util.HashMap;
4+
5+
/**
6+
* Represents a Trie Node that stores a character and pointers to its children.
7+
* Each node has a hashmap which can point to all possible characters.
8+
* Each node also has a boolean value to indicate if it is the end of a word.
9+
*/
10+
class TrieNode {
11+
char value;
12+
HashMap<Character, TrieNode> child;
13+
boolean end;
14+
15+
/**
16+
* Constructor to initialize a TrieNode with an empty hashmap
17+
* and set end to false.
18+
*/
19+
TrieNode(char value) {
20+
this.value = value;
21+
this.child = new HashMap<>();
22+
this.end = false;
23+
}
24+
}
25+
326
/**
427
* Trie Data structure implementation without any libraries.
528
* <p>
@@ -14,36 +37,20 @@
1437
* possible character.
1538
*
1639
* @author <a href="https://github.com/dheeraj92">Dheeraj Kumar Barnwal</a>
40+
* @author <a href="https://github.com/sailok">Sailok Chinta</a>
1741
*/
18-
public class TrieImp {
1942

20-
/**
21-
* Represents a Trie Node that stores a character and pointers to its children.
22-
* Each node has an array of 26 children (one for each letter from 'a' to 'z').
23-
*/
24-
public class TrieNode {
25-
26-
TrieNode[] child;
27-
boolean end;
28-
29-
/**
30-
* Constructor to initialize a TrieNode with an empty child array
31-
* and set end to false.
32-
*/
33-
public TrieNode() {
34-
child = new TrieNode[26];
35-
end = false;
36-
}
37-
}
43+
public class Trie {
44+
private static final char ROOT_NODE_VALUE = '*';
3845

3946
private final TrieNode root;
4047

4148
/**
4249
* Constructor to initialize the Trie.
4350
* The root node is created but doesn't represent any character.
4451
*/
45-
public TrieImp() {
46-
root = new TrieNode();
52+
public Trie() {
53+
root = new TrieNode(ROOT_NODE_VALUE);
4754
}
4855

4956
/**
@@ -57,13 +64,15 @@ public TrieImp() {
5764
public void insert(String word) {
5865
TrieNode currentNode = root;
5966
for (int i = 0; i < word.length(); i++) {
60-
TrieNode node = currentNode.child[word.charAt(i) - 'a'];
67+
TrieNode node = currentNode.child.getOrDefault(word.charAt(i), null);
68+
6169
if (node == null) {
62-
node = new TrieNode();
63-
currentNode.child[word.charAt(i) - 'a'] = node;
70+
node = new TrieNode(word.charAt(i));
71+
currentNode.child.put(word.charAt(i), node);
6472
}
6573
currentNode = node;
6674
}
75+
6776
currentNode.end = true;
6877
}
6978

@@ -80,13 +89,14 @@ public void insert(String word) {
8089
public boolean search(String word) {
8190
TrieNode currentNode = root;
8291
for (int i = 0; i < word.length(); i++) {
83-
char ch = word.charAt(i);
84-
TrieNode node = currentNode.child[ch - 'a'];
92+
TrieNode node = currentNode.child.getOrDefault(word.charAt(i), null);
93+
8594
if (node == null) {
8695
return false;
8796
}
8897
currentNode = node;
8998
}
99+
90100
return currentNode.end;
91101
}
92102

@@ -104,40 +114,89 @@ public boolean search(String word) {
104114
public boolean delete(String word) {
105115
TrieNode currentNode = root;
106116
for (int i = 0; i < word.length(); i++) {
107-
char ch = word.charAt(i);
108-
TrieNode node = currentNode.child[ch - 'a'];
117+
TrieNode node = currentNode.child.getOrDefault(word.charAt(i), null);
109118
if (node == null) {
110119
return false;
111120
}
121+
112122
currentNode = node;
113123
}
124+
114125
if (currentNode.end) {
115126
currentNode.end = false;
116127
return true;
117128
}
129+
118130
return false;
119131
}
120132

121133
/**
122-
* Helper method to print a string to the console.
134+
* Counts the number of words in the trie
135+
*<p>
136+
* The method traverses the Trie and counts the number of words.
123137
*
124-
* @param print The string to be printed.
138+
* @return count of words
125139
*/
126-
public static void sop(String print) {
127-
System.out.println(print);
140+
public int countWords() {
141+
return countWords(root);
142+
}
143+
144+
private int countWords(TrieNode node) {
145+
if (node == null) {
146+
return 0;
147+
}
148+
149+
int count = 0;
150+
if (node.end) {
151+
count++;
152+
}
153+
154+
for (TrieNode child : node.child.values()) {
155+
count += countWords(child);
156+
}
157+
158+
return count;
128159
}
129160

130161
/**
131-
* Validates if a given word contains only lowercase alphabetic characters
132-
* (a-z).
133-
* <p>
134-
* The method uses a regular expression to check if the word matches the pattern
135-
* of only lowercase letters.
162+
* Check if the prefix exists in the trie
136163
*
137-
* @param word The word to be validated.
138-
* @return true if the word is valid (only a-z), false otherwise.
164+
* @param prefix the prefix to be checked in the Trie
165+
* @return true / false depending on the prefix if exists in the Trie
139166
*/
140-
public static boolean isValid(String word) {
141-
return word.matches("^[a-z]+$");
167+
public boolean startsWithPrefix(String prefix) {
168+
TrieNode currentNode = root;
169+
170+
for (int i = 0; i < prefix.length(); i++) {
171+
TrieNode node = currentNode.child.getOrDefault(prefix.charAt(i), null);
172+
if (node == null) {
173+
return false;
174+
}
175+
176+
currentNode = node;
177+
}
178+
179+
return true;
180+
}
181+
182+
/**
183+
* Count the number of words starting with the given prefix in the trie
184+
*
185+
* @param prefix the prefix to be checked in the Trie
186+
* @return count of words
187+
*/
188+
public int countWordsWithPrefix(String prefix) {
189+
TrieNode currentNode = root;
190+
191+
for (int i = 0; i < prefix.length(); i++) {
192+
TrieNode node = currentNode.child.getOrDefault(prefix.charAt(i), null);
193+
if (node == null) {
194+
return 0;
195+
}
196+
197+
currentNode = node;
198+
}
199+
200+
return countWords(currentNode);
142201
}
143202
}

src/test/java/com/thealgorithms/datastructures/trees/TrieImpTest.java renamed to src/test/java/com/thealgorithms/datastructures/trees/TrieTest.java

+28-9
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
11
package com.thealgorithms.datastructures.trees;
22

3+
import static org.junit.jupiter.api.Assertions.assertEquals;
34
import static org.junit.jupiter.api.Assertions.assertFalse;
45
import static org.junit.jupiter.api.Assertions.assertTrue;
56

7+
import java.util.List;
68
import org.junit.jupiter.api.BeforeEach;
79
import org.junit.jupiter.api.Test;
810

9-
public class TrieImpTest {
10-
private TrieImp trie;
11+
public class TrieTest {
12+
private static final List<String> WORDS = List.of("Apple", "App", "app", "APPLE");
13+
14+
private Trie trie;
1115

1216
@BeforeEach
1317
public void setUp() {
14-
trie = new TrieImp();
18+
trie = new Trie();
1519
}
1620

1721
@Test
@@ -66,11 +70,26 @@ public void testInsertAndSearchPrefix() {
6670
}
6771

6872
@Test
69-
public void testIsValidWord() {
70-
assertTrue(TrieImp.isValid("validword"), "Word should be valid (only lowercase letters).");
71-
assertFalse(TrieImp.isValid("InvalidWord"), "Word should be invalid (contains uppercase letters).");
72-
assertFalse(TrieImp.isValid("123abc"), "Word should be invalid (contains numbers).");
73-
assertFalse(TrieImp.isValid("hello!"), "Word should be invalid (contains special characters).");
74-
assertFalse(TrieImp.isValid(""), "Empty string should be invalid.");
73+
public void testCountWords() {
74+
Trie trie = createTrie();
75+
assertEquals(WORDS.size(), trie.countWords(), "Count words should return the correct number of words.");
76+
}
77+
78+
@Test
79+
public void testStartsWithPrefix() {
80+
Trie trie = createTrie();
81+
assertTrue(trie.startsWithPrefix("App"), "Starts with prefix should return true.");
82+
}
83+
84+
@Test
85+
public void testCountWordsWithPrefix() {
86+
Trie trie = createTrie();
87+
assertEquals(2, trie.countWordsWithPrefix("App"), "Count words with prefix should return 2.");
88+
}
89+
90+
private Trie createTrie() {
91+
Trie trie = new Trie();
92+
WORDS.forEach(trie::insert);
93+
return trie;
7594
}
7695
}

0 commit comments

Comments
 (0)