Algo-Sim › Tries

Implement Trie (Prefix Tree)

Medium · Tries · step through it in Java, Python and C++ on your own input

Build a trie supporting insert, search (whole word) and startsWith (any prefix), each in O(word length).

Problem

Implement a prefix tree with three methods: insert(word) adds a word, search(word) returns whether that exact word was inserted, and startsWith(prefix) returns whether any inserted word begins with prefix.

Constraints

Edge cases to test

Follow-up questions

Array of 26 or hash map children?
Arrays are fast but use 26 slots per node; maps save memory for sparse or large alphabets at some speed cost.
How do you support delete?
Clear the end flag, then prune nodes on the way back up that have no children and no end flag: O(L).
How do you reduce memory?
A compressed (radix) trie merges single-child chains into one edge labelled with a string.

Solution

Java

class Trie {
    private static class Node {
        Node[] next = new Node[26];
        boolean end;
    }
    private final Node root = new Node();

    public void insert(String word) {
        Node node = root;
        for (char c : word.toCharArray()) {
            int i = c - 'a';
            if (node.next[i] == null) node.next[i] = new Node();
            node = node.next[i];
        }
        node.end = true;
    }

    public boolean search(String word) {
        Node node = find(word);
        return node != null && node.end;
    }

    public boolean startsWith(String prefix) {
        return find(prefix) != null;
    }

    private Node find(String s) {
        Node node = root;
        for (char c : s.toCharArray()) {
            node = node.next[c - 'a'];
            if (node == null) return null;
        }
        return node;
    }
}

Python

class Node:
    def __init__(self):
        self.next = [None] * 26
        self.end = False


class Trie:
    def __init__(self):
        self.root = Node()

    def insert(self, word):
        node = self.root
        for c in word:
            i = ord(c) - ord("a")
            if node.next[i] is None:
                node.next[i] = Node()
            node = node.next[i]
        node.end = True

    def search(self, word):
        node = self._find(word)
        return node is not None and node.end

    def startsWith(self, prefix):
        return self._find(prefix) is not None

    def _find(self, s):
        node = self.root
        for c in s:
            node = node.next[ord(c) - ord("a")]
            if node is None:
                return None
        return node

C++

#include <bits/stdc++.h>
using namespace std;

class Trie {
  public:
    class Node {
      public:
        vector<Node *> next = vector<Node *>(26, nullptr);
        bool end = false;
    };
    Node *root = new Node();

    void insert(string &word) {
        Node *node = root;
        for (char c : word) {
            int i = c - 'a';
            if (node->next[i] == nullptr)
                node->next[i] = new Node();
            node = node->next[i];
        }
        node->end = true;
    }

    bool search(string &word) {
        Node *node = find(word);
        return node != nullptr && node->end;
    }

    bool startsWith(string &prefix) {
        return find(prefix) != nullptr;
    }

    Node *find(string &s) {
        Node *node = root;
        for (char c : s) {
            node = node->next[c - 'a'];
            if (node == nullptr)
                return nullptr;
        }
        return node;
    }
};

More Tries problems