-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathPatriciaTrie.java
More file actions
347 lines (316 loc) · 11.3 KB
/
PatriciaTrie.java
File metadata and controls
347 lines (316 loc) · 11.3 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package com.thealgorithms.datastructures.tries;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Patricia (radix) trie for String keys and generic values.
*
* <p>Edges are compressed: each child edge stores a non-empty String label.
* Operations run in O(L) where L is the key length, with small constant factors
* from edge-label comparisons.</p>
*
* <p>Notes:
* <ul>
* <li>Null keys are not allowed (IllegalArgumentException).</li>
* <li>Empty-string key ("") is allowed as a valid key.</li>
* <li>Null values are not allowed (IllegalArgumentException).</li>
* </ul>
* </p>
*/
public final class PatriciaTrie<V> {
/** A trie node with compressed outgoing edges (label -> child). */
private static final class Node<V> {
Map<String, Node<V>> children = new HashMap<>();
boolean hasValue;
V value;
}
private final Node<V> root = new Node<>();
private int size; // number of stored keys
/** Creates an empty Patricia trie. */
public PatriciaTrie() {}
/**
* Inserts or updates the value associated with {@code key}.
*
* @param key the key (non-null; empty string allowed)
* @param value the value (non-null)
* @throws IllegalArgumentException if key or value is null
*/
public void put(String key, V value) {
if (key == null) {
throw new IllegalArgumentException("key must not be null");
}
if (value == null) {
throw new IllegalArgumentException("value must not be null");
}
insert(root, key, value);
}
/**
* Returns the value associated with {@code key}, or {@code null} if absent.
*
* @param key the key (non-null)
* @return the stored value or {@code null} if key not present
* @throws IllegalArgumentException if key is null
*/
public V get(String key) {
if (key == null) {
throw new IllegalArgumentException("key must not be null");
}
Node<V> n = findNode(root, key);
return (n != null && n.hasValue) ? n.value : null;
}
/**
* Returns true if the trie contains {@code key}.
*
* @param key the key (non-null)
* @return true if key is present
* @throws IllegalArgumentException if key is null
*/
public boolean contains(String key) {
if (key == null) {
throw new IllegalArgumentException("key must not be null");
}
Node<V> n = findNode(root, key);
return n != null && n.hasValue;
}
/**
* Removes {@code key} if present.
*
* @param key the key (non-null)
* @return true if the key existed and was removed
* @throws IllegalArgumentException if key is null
*/
public boolean remove(String key) {
if (key == null) {
throw new IllegalArgumentException("key must not be null");
}
return delete(root, key);
}
/**
* Returns true if there exists any key with the given {@code prefix}.
*
* @param prefix non-null prefix (empty prefix matches if trie non-empty)
* @return true if any key starts with {@code prefix}
* @throws IllegalArgumentException if prefix is null
*/
public boolean startsWith(String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("prefix must not be null");
}
if (prefix.isEmpty()) {
return size > 0;
}
Node<V> n = findPrefixNode(root, prefix);
return n != null;
}
/** Number of stored keys. */
public int size() {
return size;
}
/** Returns true if no keys are stored. */
public boolean isEmpty() {
return size == 0;
}
// ---------------- internal helpers ----------------
private void insert(Node<V> node, String key, V value) {
// Special case: empty remaining key => store at node
if (key.isEmpty()) {
if (!node.hasValue) {
size++;
}
node.hasValue = true;
node.value = value;
return;
}
// Find a child edge with a non-zero common prefix with 'key'
for (Map.Entry<String, Node<V>> e : node.children.entrySet()) {
String edge = e.getKey();
int cpl = commonPrefixLen(edge, key);
if (cpl == 0) {
continue;
}
// Case A: Edge fully matches the remaining key (edge == key)
if (cpl == edge.length() && cpl == key.length()) {
Node<V> child = e.getValue();
if (!child.hasValue) {
size++;
}
child.hasValue = true;
child.value = value;
return;
}
// Case B: Key is longer (edge is full prefix of key) => descend
if (cpl == edge.length() && cpl < key.length()) {
Node<V> child = e.getValue();
String rest = key.substring(cpl);
insert(child, rest, value);
// After recursion, maybe compact child (not required here)
return;
}
// Case C: Edge longer (key is full prefix of edge) OR partial split
// Need to split the existing edge.
// Split into 'prefix' (common), and two suffix edges.
String prefix = edge.substring(0, cpl);
String edgeSuffix = edge.substring(cpl); // might be non-empty
String keySuffix = key.substring(cpl); // might be empty or non-empty
// Create an intermediate node for 'prefix'
Node<V> mid = new Node<>();
node.children.remove(edge);
node.children.put(prefix, mid);
// Old child moves under 'edgeSuffix'
Node<V> oldChild = e.getValue();
if (!edgeSuffix.isEmpty()) {
mid.children.put(edgeSuffix, oldChild);
} else {
// edgeSuffix empty means 'edge' == 'prefix'; just link child
// (handled by not adding anything)
mid.children.put("", oldChild); // should not happen since cpl < edge.length()
}
// If keySuffix empty => store value at mid
if (keySuffix.isEmpty()) {
if (!mid.hasValue) {
size++;
}
mid.hasValue = true;
mid.value = value;
} else {
// Add a new leaf under keySuffix
Node<V> leaf = new Node<>();
leaf.hasValue = true;
leaf.value = value;
mid.children.put(keySuffix, leaf);
}
return;
}
// No common prefix with any child => add new edge directly
Node<V> leaf = new Node<>();
leaf.hasValue = true;
leaf.value = value;
node.children.put(key, leaf);
size++;
}
private Node<V> findNode(Node<V> node, String key) {
if (key.isEmpty()) {
return node;
}
for (Map.Entry<String, Node<V>> e : node.children.entrySet()) {
String edge = e.getKey();
int cpl = commonPrefixLen(edge, key);
if (cpl == 0) {
continue;
}
if (cpl == edge.length()) {
// Edge fully matches a prefix of key
String rest = key.substring(cpl);
return findNode(e.getValue(), rest);
} else {
// Partial match but edge not fully consumed => key absent
return null;
}
}
return null;
}
private Node<V> findPrefixNode(Node<V> node, String prefix) {
if (prefix.isEmpty()) {
return node;
}
for (Map.Entry<String, Node<V>> e : node.children.entrySet()) {
String edge = e.getKey();
int cpl = commonPrefixLen(edge, prefix);
if (cpl == 0) {
continue;
}
if (cpl == prefix.length()) {
// consumed the whole prefix: prefix exists in this subtree
return e.getValue();
}
if (cpl == edge.length()) {
// consume edge, continue with remaining prefix
String rest = prefix.substring(cpl);
return findPrefixNode(e.getValue(), rest);
}
// partial split where neither fully consumed => no such prefix path
return null;
}
return null;
}
private boolean delete(Node<V> node, String key) {
if (key.isEmpty()) {
if (!node.hasValue) {
return false;
}
node.hasValue = false;
node.value = null;
size--;
// After removing value at this node, maybe merge if only one child
// (merging handled by caller via cleanup step)
return true;
}
// Find matching child by common prefix
for (Map.Entry<String, Node<V>> e : node.children.entrySet()) {
String edge = e.getKey();
int cpl = commonPrefixLen(edge, key);
if (cpl == 0) {
continue;
}
if (cpl < edge.length()) {
// Partial overlap (edge not fully matched) -> key not present
return false;
}
// Edge fully matched; go deeper
String rest = key.substring(cpl);
Node<V> child = e.getValue();
boolean removed = delete(child, rest);
if (!removed) {
return false;
}
// Cleanup/merge after successful deletion
mergeIfNeeded(node, edge, child);
return true;
}
return false;
}
/**
* If the child at {@code parent.children[edge]} can be merged up (no value and
* a single child), compress the two edges into one. Also, if the child has no
* value and no children, remove it.
*/
private void mergeIfNeeded(Node<V> parent, String edge, Node<V> child) {
if (child.hasValue) {
// Can't merge if child holds a value
return;
}
int deg = child.children.size();
if (deg == 0) {
// Remove empty child
parent.children.remove(edge);
return;
}
if (deg == 1) {
// Merge child's only edge into parent edge: edge + subEdge
Map.Entry<String, Node<V>> only = child.children.entrySet().iterator().next();
String subEdge = only.getKey();
Node<V> grand = only.getValue();
parent.children.remove(edge);
parent.children.put(edge + subEdge, grand);
}
}
/** Returns length of common prefix of a and b (0..min(a.length,b.length)). */
private static int commonPrefixLen(String a, String b) {
int n = Math.min(a.length(), b.length());
int i = 0;
while (i < n && a.charAt(i) == b.charAt(i)) {
i++;
}
return i;
}
@Override
public int hashCode() {
// not used by algorithms; keep minimal but deterministic with size
return Objects.hash(size);
}
@Override
public boolean equals(Object obj) {
// Structural equality is not required; keep reference equality
return this == obj;
}
}