AlgoMaster Logo

Design Add and Search Words Data Structure

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

We can store each added word in a list and when a search operation is called, we'll iterate through all the stored words to check if there's any match to the search word. For search words having a wildcard character '.', we need to check each character except the wildcard positions. This approach is inefficient for large datasets due to the linear search which is coupled with string matching complexity.

Code:

2. Trie Implementation

Intuition:

A more efficient approach is to use a Trie (prefix tree) to store the added words. The trie allows us to efficiently search by traversing down the tree character by character, matching the structure of the search word. For each wildcard '.', we can traverse down all possible paths. This significantly reduces the time complexity for search operations compared to the brute force method.

Code: