0% found this document useful (0 votes)
31 views2 pages

Aaps SolQ40

The document describes the implementation of a Trie data structure that supports insert, search, and startsWith operations for lowercase English words. It outlines the algorithm using a tree of TrieNodes with 26 children, detailing the time complexity as O(n) per operation and space complexity as O(n * k) for inserted words. Java code is provided to illustrate the implementation of the Trie and its methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views2 pages

Aaps SolQ40

The document describes the implementation of a Trie data structure that supports insert, search, and startsWith operations for lowercase English words. It outlines the algorithm using a tree of TrieNodes with 26 children, detailing the time complexity as O(n) per operation and space complexity as O(n * k) for inserted words. Java code is provided to illustrate the implementation of the Trie and its methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Question 40: Implement Trie (Prefix Tree)

Question (from PDF): Implement a Trie data structure to support insert, search, and startsWith
operations efficiently. Each node should represent a character from a lowercase English word.

Problem: Implement a Trie with insert, search, and startsWith operations.

Algorithm: - Use a tree of TrieNodes with 26 children.

Time Complexity: O(n) per operation


Space Complexity: O(n * k) for inserted words

Java Code:

class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEndOfWord;
}

public class Trie {


private TrieNode root;

public Trie() {
root = new TrieNode();
}

public void insert(String word) {


TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null)
node.children[index] = new TrieNode();
node = node.children[index];
}
node.isEndOfWord = true;
}

public boolean search(String word) {


TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) return false;
node = node.children[index];
}
return node.isEndOfWord;
}

public boolean startsWith(String prefix) {


TrieNode node = root;

1
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) return false;
node = node.children[index];
}
return true;
}
}

You might also like