0
0
DSA Javascriptprogramming~3 mins

Why Word Search in Trie in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

What if you could find any word instantly without flipping through pages?

The Scenario

Imagine you have a huge dictionary of words written on paper. You want to find if a word exists, but you have to flip through every page and every word one by one.

The Problem

This manual search is very slow and tiring. It takes a lot of time to check each word, and you might make mistakes or miss words because of the long list.

The Solution

A Trie is like a smart tree that organizes words by their letters. It helps you quickly jump to the right place for each letter, so you can find words fast without checking everything.

Before vs After
Before
function searchWord(words, target) {
  for (let word of words) {
    if (word === target) return true;
  }
  return false;
}
After
class TrieNode {
  constructor() {
    this.children = {};
    this.isWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }
  insert(word) {
    let current = this.root;
    for (let letter of word) {
      if (!current.children[letter]) {
        current.children[letter] = new TrieNode();
      }
      current = current.children[letter];
    }
    current.isWord = true;
  }
  search(word) {
    let current = this.root;
    for (let letter of word) {
      if (!current.children[letter]) return false;
      current = current.children[letter];
    }
    return current.isWord;
  }
}
What It Enables

With a Trie, you can find words instantly, even in huge lists, making searching fast and reliable.

Real Life Example

When you type on your phone keyboard, the system quickly suggests words by searching a Trie of all possible words, so you get instant suggestions.

Key Takeaways

Manual word search is slow and error-prone.

Trie organizes words by letters for fast searching.

Using Trie makes word search quick and efficient.