Browse curriculum

Prefix Matching

Prefix Matching: use Trie to efficiently find all keys matching a prefix.

Medium

Problem Understanding

This is essentially startsWith but often implies retrieving related data or completing the word. In this lesson, we use the standard startsWith logic as the core building block for Autocomplete systems.

Algorithm Strategy

  1. Start at the Trie root.
  2. Iterate through each character of the prefix.
  3. Check if the current node has a child for that character.
  4. If No: Prefix doesn't exist. Return False.
  5. If Yes: Move to that child node.
  6. If loop completes: The path exists. Return True (unlike Search, we ignore isEnd).

Interactive Visualization

PREFIX "ap" · GREEN = END OF A STORED WORD

TRIE BUILT

Checked

0

Depth

0

Returns

:

 

The trie holds "apple", "apply", "apt", "bat"

Next

startsWith("ap"): start at the root

Free preview: the first 3 of 5 steps

Words

Prefix

See how startsWith confirms if a path exists without requiring the isEnd flag.

Dry Run: startsWith('ap')

Trie has 'apple'.

Char Child Exists? Action
'a' Yes Move to 'a'.
'p' Yes Move to 'p'.
End - Loop done. Path exists. Return True.

Edge Cases & Checks

Important checks:

  • No Matches: Return valid value (false/empty list).

  • Empty Prefix: Matches every stored word: the loop never runs and startsWith returns true.

  • Case: Ensure 'A' doesn't match 'a' without normalization.

Solution (StartsWith Logic)

O(L) Time.

Prefix Matching Code
1Trie.prototype.startsWith = function(prefix) {
2 let node = this;
3 for(const char of prefix) {
4 if(!node.children[char]) return false;
5 node = node.children[char];
6 }
7 return true;
8};

Prefix Matching in Python, Java, C++, TypeScript and C

Prefix Matching in Python
def startsWith(self, prefix: str) -> bool:
    node = self.root
    for char in prefix:
        if char not in node.children:
            return False
        node = node.children[char]
    return True
Prefix Matching in Java
public 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;
}
Prefix Matching in C++
bool startsWith(string prefix) {
    TrieNode* node = root;
    for(char c : prefix) {
        int idx = c - 'a';
        if(!node->children[idx]) return false;
        node = node->children[idx];
    }
    return true;
}
Prefix Matching in TypeScript
startsWith(prefix: string): boolean {
    let node: Trie = this;
    for (const char of prefix) {
        if (!node.children[char]) return false;
        node = node.children[char];
    }
    return true;
}
Prefix Matching in C
bool trieStartsWith(Trie* obj, char * prefix) {
    Trie* node = obj;
    for(int i=0; prefix[i] != '\0'; i++) {
        int idx = prefix[i] - 'a';
        if(node->children[idx] == NULL) return false;
        node = node->children[idx];
    }
    return true;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start at the root

    Take the trie's root as the current node.

  2. Follow each character

    For every character of the prefix, move to that child, or return false if it is missing.

  3. Return true

    If every character was found, the prefix path exists: return true.

Frequently asked questions

How does prefix matching work in a trie?

Start at the root and follow the child for each character of the prefix. If any child is missing, no stored word has that prefix; if the walk finishes, at least one does.


Why does startsWith ignore the end-of-word flag?

A prefix only needs its path to exist. The node where the walk stops may sit in the middle of a longer word, such as "ap" inside "apple", and it still counts as a match.


What is the time complexity of prefix matching in a trie?

O(L) time for a prefix of length L, since each character costs one child lookup, and O(1) extra space because the walk only keeps a reference to the current node.

New to the technique behind this problem? Watch it run step by step:

Trie (Prefix Tree) Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description