Contacts

  • + 0 comments

    Java O(n L)

     class TrieNode {
            Map<Character, TrieNode> children = new HashMap<>();
            int count = 0;
        }
    
         class Result {
            public static List<Integer> contacts(List<List<String>> queries) {
                TrieNode root = new TrieNode();
                List<Integer> results = new ArrayList<>();
    
                for (List<String> query : queries) {
                    String operation = query.get(0);
                    String value = query.get(1);
    
                    if (operation.equals("add")) {
                        addContact(root, value);
                    } else if (operation.equals("find")) {
                        results.add(findPartial(root, value));
                    }
                }
    
                return results;
            }
    
            private static void addContact(TrieNode root, String contact) {
                TrieNode current = root;
                for (char c : contact.toCharArray()) {
                    current.children.putIfAbsent(c, new TrieNode());
                    current = current.children.get(c);
                    current.count++;
                }
            }
    
            private static int findPartial(TrieNode root, String prefix) {
                TrieNode current = root;
                for (char c : prefix.toCharArray()) {
                    current = current.children.get(c);
                    if (current == null) {
                        return 0;
                    }
                }
                return current.count;
            }
        }