Bird
Raised Fist0
DSA Goprogramming

Trie Search Operation in DSA Go

Choose your learning style10 modes available
Mental Model
A trie stores words by branching letters step-by-step. Searching means following branches for each letter to see if the word exists.
Analogy: Imagine a tree where each branch is a letter. To find a word, you walk down the branches letter by letter until you reach the end of the word or get stuck.
root
 ↓
 a -> b -> c -> null
 ↓
 t (end)

Each arrow shows the next letter branch. 't (end)' means word ends here.
Dry Run Walkthrough
Input: Trie with words: "cat", "car", "bat"; search for "car"
Goal: Check if the word "car" exists in the trie
Step 1: Start at root node, look for branch 'c'
root -> [c] -> a -> t/null and r/null branches
Why: We must find the first letter 'c' to continue searching
Step 2: Move to node 'c', look for branch 'a'
root -> c -> [a] -> t/null and r/null branches
Why: Next letter 'a' must be found under 'c'
Step 3: Move to node 'a', look for branch 'r'
root -> c -> a -> [r] (end of word)
Why: Last letter 'r' must be found to confirm word
Step 4: Check if 'r' node marks end of word
root -> c -> a -> r (end)
Why: Only if this node marks end of word, 'car' exists
Result:
root -> c -> a -> r (end) confirms word "car" exists
Annotated Code
DSA Go
package main

import "fmt"

// TrieNode represents each node in the trie
type TrieNode struct {
	children map[rune]*TrieNode
	isEnd bool
}

// Trie structure with root node
type Trie struct {
	root *TrieNode
}

// NewTrieNode creates a new trie node
func NewTrieNode() *TrieNode {
	return &TrieNode{children: make(map[rune]*TrieNode)}
}

// NewTrie creates a new trie
func NewTrie() *Trie {
	return &Trie{root: NewTrieNode()}
}

// Insert adds a word to the trie
func (t *Trie) Insert(word string) {
	curr := t.root
	for _, ch := range word {
		if curr.children[ch] == nil {
			curr.children[ch] = NewTrieNode() // create branch if missing
		}
		curr = curr.children[ch] // move to next node
	}
	curr.isEnd = true // mark end of word
}

// Search checks if a word exists in the trie
func (t *Trie) Search(word string) bool {
	curr := t.root
	for _, ch := range word {
		if curr.children[ch] == nil {
			return false // missing letter branch means word not found
		}
		curr = curr.children[ch] // move to next node
	}
	return curr.isEnd // true only if end of word
}

func main() {
	trie := NewTrie()
	trie.Insert("cat")
	trie.Insert("car")
	trie.Insert("bat")

	fmt.Println(trie.Search("car")) // true
	fmt.Println(trie.Search("cap")) // false
}
if curr.children[ch] == nil {
check if current letter branch exists
curr = curr.children[ch]
advance to next node along letter branch
return false
stop search early if letter branch missing
return curr.isEnd
confirm word exists only if last node marks end
OutputSuccess
true false
Complexity Analysis
Time: O(m) because we check each of the m letters in the word once
Space: O(1) for search since no extra space grows with input size
vs Alternative: Compared to searching in a list of words (O(n*m)), trie search is faster because it directly follows letter branches
Edge Cases
search empty string
returns false because no word is empty
DSA Go
return curr.isEnd // true only if end of word
search word not inserted
returns false when a letter branch is missing
DSA Go
if curr.children[ch] == nil { return false }
search prefix of a word but not a full word
returns false because isEnd is false at last node
DSA Go
return curr.isEnd
When to Use This Pattern
When you need to quickly check if words or prefixes exist in a set, use trie search because it follows letter branches step-by-step.
Common Mistakes
Mistake: Not checking if the last node marks the end of a word
Fix: Always check the isEnd flag after traversing all letters
Mistake: Returning true as soon as all letters are found without isEnd check
Fix: Return true only if the last node's isEnd is true
Summary
It checks if a word exists by following letter branches in the trie.
Use it when you want fast word lookups in a large dictionary.
The key is to follow each letter branch and confirm the word ends exactly there.

Practice

(1/5)
1. What does the search operation in a Trie data structure check for?
easy
A. The number of words stored in the Trie
B. If the Trie is empty
C. If a given word exists in the Trie
D. The length of the longest word in the Trie

Solution

  1. Step 1: Understand the purpose of Trie search

    The search operation in a Trie is designed to check if a specific word is stored in the Trie.
  2. Step 2: Differentiate from other Trie operations

    Other operations like counting words or checking emptiness are not the purpose of search.
  3. Final Answer:

    If a given word exists in the Trie -> Option C
  4. Quick Check:

    Trie search checks word existence [OK]
Hint: Search checks if the exact word is stored [OK]
Common Mistakes:
  • Confusing search with counting words
  • Thinking search checks Trie emptiness
  • Assuming search returns word length
2. Which of the following is the correct way to check if a character node exists in a Trie map in Go?
easy
A. if node.children[char] != nil
B. if node.children[char] == nil
C. if node.children.contains(char)
D. if node.children.has(char)

Solution

  1. Step 1: Recall Go map access syntax

    In Go, to check if a key exists in a map, you check if the value is not nil (for pointer or map values).
  2. Step 2: Apply to Trie children map

    Trie children are stored in a map from rune to *TrieNode, so checking if node.children[char] != nil confirms existence.
  3. Final Answer:

    if node.children[char] != nil -> Option A
  4. Quick Check:

    Go map key exists check [OK]
Hint: Check map key by comparing to nil in Go [OK]
Common Mistakes:
  • Using contains or has methods (not in Go maps)
  • Checking for equality to nil incorrectly
  • Confusing map key existence with value presence
3. Consider the following Go code snippet for searching a word in a Trie:
func (t *Trie) Search(word string) bool {
    node := t.root
    for _, ch := range word {
        if node.children[ch] == nil {
            return false
        }
        node = node.children[ch]
    }
    return node.isEnd
}
What will be the output of Search("cat") if the Trie contains the words "car", "cat", and "cap"?
medium
A. compilation error
B. true
C. runtime error
D. false

Solution

  1. Step 1: Trace the search for "cat" in the Trie

    The loop checks each character 'c', 'a', 't' in order. Since "cat" is inserted, all nodes exist and node.isEnd is true at 't'.
  2. Step 2: Return value after traversal

    Because node.isEnd is true at the last character, the function returns true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Word "cat" exists in Trie = true [OK]
Hint: Search returns true if last node marks word end [OK]
Common Mistakes:
  • Ignoring isEnd flag and returning true always
  • Assuming false if any child exists
  • Confusing runtime errors with nil checks
4. The following Go code for Trie search has a bug. What is the error?
func (t *Trie) Search(word string) bool {
    node := t.root
    for i := 0; i <= len(word); i++ {
        ch := rune(word[i])
        if node.children[ch] == nil {
            return false
        }
        node = node.children[ch]
    }
    return node.isEnd
}
medium
A. Missing check for empty Trie root
B. Incorrect rune conversion for characters
C. Returning wrong boolean value
D. Index out of range error due to loop condition

Solution

  1. Step 1: Analyze the loop condition

    The loop runs from i = 0 to i <= len(word), which means it tries to access word[len(word)] causing index out of range error.
  2. Step 2: Correct loop boundary

    The loop should run with i < len(word) to avoid accessing beyond the string length.
  3. Final Answer:

    Index out of range error due to loop condition -> Option D
  4. Quick Check:

    Loop boundary error causes runtime panic [OK]
Hint: Use i < len(word), not i <= len(word) in loops [OK]
Common Mistakes:
  • Using <= instead of < in loop
  • Ignoring string length limits
  • Assuming rune conversion causes error
5. You want to modify the Trie search function to support prefix search (check if any word starts with the given prefix). Which change is correct?
hard
A. Return true immediately after traversing all prefix characters without checking isEnd
B. Return true only if isEnd is true at last prefix character
C. Return false if any character node is missing, else return false always
D. Return true only if prefix length equals word length stored

Solution

  1. Step 1: Understand prefix search goal

    Prefix search should return true if the prefix exists as a path in the Trie, regardless of isEnd flag.
  2. Step 2: Modify search to return true after prefix traversal

    After checking all prefix characters exist, return true immediately without checking isEnd.
  3. Final Answer:

    Return true immediately after traversing all prefix characters without checking isEnd -> Option A
  4. Quick Check:

    Prefix search ignores isEnd, returns true if path exists [OK]
Hint: For prefix, return true after full prefix traversal [OK]
Common Mistakes:
  • Checking isEnd for prefix search
  • Returning false even if prefix path exists
  • Confusing prefix length with word length
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard