0
0
DSA Typescriptprogramming~3 mins

Why Trie Insert Operation in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could find or add any word instantly, no matter how big your list is?

The Scenario

Imagine you have a huge phone book written on paper. You want to find or add a new name quickly, but you have to flip through every page one by one.

It takes a lot of time and you might lose your place or make mistakes.

The Problem

Manually searching or adding names in a big list is slow and tiring.

You can easily miss names or add duplicates because you have no quick way to check if a name exists.

It's like looking for a word in a dictionary without alphabetical order.

The Solution

A Trie is like a smart tree that stores words letter by letter.

When you add a word, you follow the path of letters and create new branches only if needed.

This way, you quickly find or add words without checking the whole list.

Before vs After
Before
let phoneBook = [];
// To add a name
phoneBook.push('Alice');
// To check if name exists
phoneBook.includes('Alice');
After
class TrieNode {
  children: Map<string, TrieNode> = new Map();
  isWordEnd: boolean = false;
}

class Trie {
  root = new TrieNode();
  insert(word: string) {
    let current = this.root;
    for (const letter of word) {
      if (!current.children.has(letter)) {
        current.children.set(letter, new TrieNode());
      }
      current = current.children.get(letter)!;
    }
    current.isWordEnd = true;
  }
}
What It Enables

It lets you add and find words instantly, even in huge lists, by following letter paths.

Real Life Example

Autocomplete in search engines uses Tries to quickly suggest words as you type each letter.

Key Takeaways

Manual searching is slow and error-prone for large word lists.

Trie stores words letter by letter, making insertions fast and organized.

It enables quick word lookup and autocomplete features.