Cracking the Coding Interview: Tries – Contacts

Here’s my solution to the challenge: https://www.hackerrank.com/challenges/ctci-contacts

const int NUM_CHARACTERS = 26;

class Node {
    Node* children[NUM_CHARACTERS];
    int size = 0;
    
public:
    int getCharIndex(char c){
        return c - 'a';
    }
    Node* getNode(char c){
        return children[getCharIndex(c)];
    }
    void setNode(char c, Node* node){
        children[getCharIndex(c)] = node;
    }
    void add(string s, int index){
        size++;
        if(index == s.length())
            return;
        char current = s[index];
        Node* child = getNode(current);
        if(child == NULL){
            child = new Node();
            setNode(current, child);
        }
        child->add(s, index + 1);
    }
    int findCount(string s, int index){
        if(index == s.length())
            return size;
        Node* child = getNode(s[index]);
        if(child == NULL)
            return 0;
        return child->findCount(s, index + 1);
    }
};

int main(){
    int n;
    cin >> n;
    Node* root = new Node();
    for(int a0 = 0; a0 > op >> contact;
        if(op == "add")
            root->add(contact, 0);
        else if(op == "find")
            cout <findCount(contact, 0) << endl;
    }
    return 0;
}

All my solutions to HackerRank challenges can be found here: https://github.com/sdulaney/hackerrank

Leave a Comment