← Infosys bank

Infosys · Question 64 · Trees

Implement Trie (Prefix Tree)

TreesC++code⏱ O(m)💾 O(n*m)
Service-based

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

  1. 1Insert walks/creates child links per letter.
  2. 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.
↻ repeatSTARTinclude <iostream>include <string>include <vector>using namespace stdCLASS TrieNodeDEFINETrieNode* children[26]bool isEndTrieNode()CLASS TrieTrieNode* rootDEFINETrie() { root = newTrieNode(); }DEFINE insert(string word)TrieNode* node = rootfor (char c : word)DEFINE idx = c - 'a'if(!node->children[idx])node->children[idx] …node = node->children[idx]node->isEnd = truebool search(string word)bool startsWith(stringprefix)DEFINE main()Trie trietrie.insert("apple")cout << "[" <<trie.search("apple") << "," << trie.search("app") <…RETURN 0END
  • 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