C++ Implementation of Trie Data Structure using Hash Map

in #programming6 years ago

Trie is a useful data structure allow us to search a given word or check if any words start with prefix in O(N) efficient time. The following is the C++ implementation of Trie Class which is based on unordered_map hash map instead of a fix-size e.g. 26 children. The advantages of doing so is that we can use the Trie class in basically any character set (not just English lowercase/uppercase).

class Trie {
    public:
    Trie() {
        leaf = false;
    }

    unordered_map<char, Trie*> children;
    bool leaf;
    
    void add(string s) {
        auto root = this;
        for (const auto &n: s) {
            if (!root->children[n]) {
                root->children[n] = new Trie();
            }
            root = root->children[n];
        }
        root->leaf = true;
    }

    bool exists(string word) {
        auto root = this;
        for (const auto &n: word) {
            if (!root->children[n]) {
                return false;
            }
            root = root->children[n];
        }        
        return root && root->leaf;
    }

    bool startswith(string p) {
        auto root = this;
        for (const auto &n: p) {
            if (!root->children[n]) {
                return false;
            }
            root = root->children[n];
        }        
        return root != NULL;      
    }
};

The space complexity for Trie class is often O(MN) where M is the number of strings to add and the N is the average length of the words. The time complexity of Trie is O(N) where N is the length of the given string to lookup, add or check if any starts with it (prefix check).

We can use the Trie in the following way:

Trie trie;
trie.add("hello");
trie.startswith("hel"); // true
trie.exists("hel"); // false

Here is a Python's implementation of the Trie Data Structure.

--EOF (The Ultimate Computing & Technology Blog) --

Reposted to Algorithms, Blockchain and Cloud


Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Support me

If you like my work, please:

Sort:  

!shop
$trdo

你好鸭,justyy!

@eii给您叫了一份外卖!

奶黄包

吃饱了吗?跟我猜拳吧! 石头,剪刀,布~

如果您对我的服务满意,请不要吝啬您的点赞~

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.088
BTC 59993.95
ETH 1578.05
USDT 1.00
SBD 0.42