DSA Tracker

Medium

Implement Trie (Prefix Tree)

A medium Trie problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Trie
Sheets
3
Core for
7 roles
Platform
LeetCode

The problem

Design a tree-based data structure that stores a collection of strings so that you can efficiently check whether a string exists in the set, and whether any string in the set begins with a given prefix.

Example 1

Input
insert("apple"), search("apple"), search("app"), startsWith("app")
Output
true, false, true
Why
After inserting 'apple', searching for the exact string 'apple' returns true. Searching for 'app' as a complete string returns false because 'app' was never inserted. The prefix 'app' exists because it is the start of 'apple'.

Example 2

Input
insert("app"), search("app")
Output
true

Constraints

  • 1 <= total length of all inserted strings <= 10^4
  • Strings consist of lowercase English letters
  • At most 10^4 calls in total

How to think about it

Updated 2026-09-09

A hash table treats whole strings as opaque blobs, so discovering common prefixes forces an scan over every stored key. Splitting strings by character turns prefix matching into following a path down a shared tree: any path that survives to the prefix end proves existence instantly, without checking irrelevant branches.

Approaches, worst first

  1. List scan

    time O(n * L) · space O(total characters)

    Keep an array of inserted strings. Exact search checks equality, prefix search runs startsWith against every element. Short to write, but every prefix lookup pays for the entire dictionary size.

  2. Hash set prefix tracking

    time O(L) · space O(total characters * L)

    Store exact words in one set and all prefixes of every word in another. Prefix queries become instantaneous O(L) lookups, but every insertion of length L adds L distinct string slices into memory.

  3. Prefix treeWrite this one

    time O(L) · space O(total characters)

    Represent characters as edges or fixed-size child arrays of size 26. Walk down one node per character of the query. For prefix match, reachability is enough; for exact match, inspect an isTerminal boolean flag on the arrival node.

Where people lose marks · 3
  • Confusing prefix presence with word presence. Forgetting the terminal flag causes search for app to return true when only apple was ever inserted.
  • Allocating fixed 26-element arrays on every node upfront consumes significant memory when branches are sparse; map or null-initialized pointers avoid this.
  • Off-by-one indexing characters with charCodeAt: subtracting lowercase a maps letters to 0 through 25, but non-lowercase inputs break array indexing.

The theory behind it

Trie — the ground this problem stands on. All Trie problems

What Trie is

A trie, also called a prefix tree, is a tree structured for storing words character by character. Instead of storing entire words in individual nodes, each step down a branch represents a single letter. Words that share the same beginning, like car, card, and care, share the exact same starting path down the tree. A special boolean marker sits at the end of each valid word to show that a complete word terminates at that letter.

When to reach for it

Reach for a trie when questions involve prefix lookups, dictionary word searches, autocomplete engines, or matching prefixes against a body of text. Prompts asking whether any word in a dictionary begins with a given prefix, or searching for words on a Boggle board grid, point directly to a trie. It also applies to bitwise tasks, such as finding the maximum XOR pair among integers by treating numbers as binary prefixes.

How the pattern works

Represent each trie node with an array or hash map of child links, plus a boolean flag marking if a complete word ends at that node. When inserting, start at the root and walk down character by character, creating new child nodes whenever a path does not exist yet, then mark the final node as a word ending. When searching, follow the characters; if any child link is missing, the word or prefix does not exist. If all characters match, check the boolean flag to distinguish between a full word and a partial prefix.

What each operation costs

OperationTime
insert word of length l into trieO(l)
search for full word of length lO(l)
check if any word begins with prefix of length lO(l)
What usually goes wrong with Trie
  • Confusing prefix matches with full word matches by returning true when characters exist but the end-of-word flag on the final node was never set.
  • Allocating fixed 26-slot arrays for child pointers without verifying that all input characters are strictly lowercase English letters.
  • Forgetting to prune unvisited branches during board searches, leading to time limit exceeded errors on grids with large word sets.

Which roles need this problem

Trie is a core topic for these 7 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 2 more roles, including Information Retrieval Engineer, Storage Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Trie problems

Problem set and role mapping as of .