class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEnd = false; } class Trie { TrieNode root = new TrieNode(); void insert(String word) { TrieNode node = root; for (char c : word.toCharArray()) { int idx = c - 'a'; if (node.children[idx] == null) { node.children[idx] = new TrieNode(); } node = node.children[idx]; } node.isEnd = true; } boolean startsWith(String prefix) { TrieNode node = root; for (char c : prefix.toCharArray()) { int idx = c - 'a'; if (node.children[idx] == null) return false; node = node.children[idx]; } return true; } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); trie.insert("apple"); trie.insert("app"); System.out.println(trie.startsWith("app")); System.out.println(trie.startsWith("apl")); } }
The prefix "app" exists in the Trie because "apple" and "app" were inserted. The prefix "apl" does not exist, so the output is true then false.
Trie stores words in a tree structure where common prefixes share nodes, allowing efficient prefix search. Hash Map requires checking all keys or additional structures.
import java.util.*; public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("app", 2); map.put("banana", 3); for (String key : map.keySet()) { if (key.startsWith("app")) { System.out.println(key + ": " + map.get(key)); } } } }
The code iterates over keys and prints those starting with "app" without modifying the map, so no error occurs.
import java.util.*; public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("cat", 1); map.put("car", 2); map.put("dog", 3); List<String> result = new ArrayList<>(); for (String key : map.keySet()) { if (key.startsWith("ca")) { result.add(key); } } Collections.sort(result); System.out.println(result); } }
Keys "car" and "cat" start with "ca". After sorting alphabetically, the list is [car, cat].
Trie shares nodes for common prefixes, reducing memory for overlapping parts. Hash Map stores each key string fully, increasing memory when many keys share prefixes.
