0
0
DSA Javascriptprogramming~3 mins

Why Prefix Search Using Trie in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

What if you could find all words starting with 'Sam' instantly, no matter how big the list?

The Scenario

Imagine you have a huge phone book and you want to find all contacts starting with 'Sam'. You try to look through every name one by one, which takes forever.

The Problem

Searching manually means checking each name from start to end. This is slow and tiring, especially if the list is very long. You might miss some names or get frustrated.

The Solution

A Trie is like a smart tree that organizes words by their letters. It lets you jump straight to all names starting with 'Sam' without checking every single name.

Before vs After
Before
function searchPrefix(words, prefix) {
  let results = [];
  for (let word of words) {
    if (word.startsWith(prefix)) results.push(word);
  }
  return results;
}
After
class TrieNode {
  constructor() {
    this.children = {};
    this.isEnd = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }
  // insert and prefix search methods here
}
What It Enables

It makes finding all words with a given start lightning fast, even in huge collections.

Real Life Example

Search engines use prefix search to suggest words as you type, showing results instantly.

Key Takeaways

Manual search checks every word, which is slow.

Trie organizes words by letters for quick prefix lookup.

Prefix search with Trie is fast and efficient for large data.