No Prefix Set

  • + 0 comments

    It can be solved with a custom trie.

    class Trie {
    public:
        bool insert(string word) {
            if (!head) {
                head.reset(make_node(L'\0'));
            }
            
            bool foundPrefix = true;
            auto working = head.get();
            for (auto c : word) {
                const auto idx = c - 'a';       
                if (working->isLeaf) {
                    // hit a prefix trying to insert the word
                    return true;
                }
                
                if (!working->children[idx]) {
                    // we are appending to the trie, so no prefix was found.
                    working->children[idx].reset(make_node(c));  
                    foundPrefix = false;
                }
                
                working = working->children[idx].get();
            }
            
            if (working) {
                working->isLeaf = true;
            }
            
            return foundPrefix;
        }
        
    private:
        struct Node {
            char data;
            std::unique_ptr<Node> children[10];
            bool isLeaf;
        };
        
        Node* make_node(char d) {
            return new Node{ d, {}, false };
        }
        
        std::unique_ptr<Node> head{};
    };
    
    void noPrefix(vector<string> words) {
        Trie t;
        for (auto word : words) {
            if (t.insert(word))
            {
                printf("BAD SET\n");
                printf("%s\n", word.c_str());
                return;
            }
        }
        
        printf("GOOD SET\n");
    }