Infosys · Question 64 · Trees
Implement Trie (Prefix Tree)
Problem
Implement a trie with insert, search, and startsWith methods.
Approach
Use a tree structure where each node contains links to child nodes and a flag for word end.
Time O(m)Space O(n*m)
How it works
- 1Insert walks/creates child links per letter.
- 2Search needs the end flag; prefix only needs the path.
Sample input / output
Input:
ops = [insert("apple"), search("apple"), search("app"), startsWith("app")]
Output:
[1, 0, 1]Constraints
Lowercase words; 1 <= word.length <= 2000.
Solution — read it, then walk it
Time O(m)Space O(n*m)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/28
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits