Implement tries and graph representations
Implement tries and graph representations
A trie stores strings as paths through a tree of symbols. Shared prefixes reuse nodes; a terminal flag distinguishes a complete word from a prefix. A graph may instead connect arbitrary vertices, including cycles. Its adjacency representation should suit the operations and edge density.
package main
import ( "fmt")
type Trie struct { next map[rune]*Trie end bool}
func (t *Trie) Insert(s string) { for _, c := range s { if t.next == nil { t.next = make(map[rune]*Trie) } if t.next[c] == nil { t.next[c] = &Trie{} } t = t.next[c] } t.end = true}func (t *Trie) Has(s string) bool { for _, c := range s { t = t.next[c] if t == nil { return false } } return t.end}func main() { var t Trie t.Insert("go") t.Insert("gone") t.Insert("سلام") fmt.Println(t.Has("go"), t.Has("gon"), t.Has("سلام"), t.Has(""))}Each range step uses a rune, not a byte. end is true only for inserted words, including the empty word if explicitly inserted. Work scales with the number of runes and map operations; per-node maps can be expensive. The zero-value root is usable, but a nil root is not. The word contract is valid UTF-8. Invalid byte sequences can decode to the same replacement rune; validate external input if exact byte identity matters. Unicode normalization is not performed.
Expected output:
true false true falseCompare adjacency lists and matrices
package main
import ( "fmt")
func main() { g := [][]int{{1, 2}, {2}, nil} m := make([][]bool, len(g)) for i, neighbors := range g { m[i] = make([]bool, len(g)) for _, j := range neighbors { m[i][j] = true } } fmt.Println(m[0][2], m[2][0], len(g[0]))}This directed graph uses vertex indices 0 through V-1. The adjacency list costs O(V+E) storage and enumerates neighbors directly; the matrix costs O(V²) and tests an edge in O(1). The boolean matrix collapses repeated edges. Validate indices; for undirected graphs store both directions, taking care with self-loops.
Expected output:
true false 2Try it locally
Construct an undirected adjacency list with 4 vertices and edges (0,1), (1,2). Print neighbors of vertex 1 and the degree of isolated vertex 3.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 05: Implement tries and graph representations
Check the lesson objective before moving on.
Why does a trie need a terminal flag?
What is adjacency matrix storage for V vertices?