Sort by

recency

|

333 Discussions

|

  • + 0 comments

    C# solution using a tree where each node has potentially 26 children.

    class Result
    {     
        class Node
        {
            public int Count = 0;
            public Node[] Children = new Node[26];        
        }
    
        public static List<int> contacts(List<List<string>> queries)
        {
            List<int> counts = new List<int>();
            Node root = new Node();
            
            foreach (List<string> q in queries)
            {
                if (q[0] == "add")
                {
                    Node currentNode = root;
                    foreach (char c in q[1])
                    {
                        if (currentNode.Children[c - 'a'] == null)
                        {
                            Node n = new Node();
                            n.Count = 1;
                            currentNode.Children[c - 'a'] = n;                        
                        }
                        else 
                        {
                            currentNode.Children[c - 'a'].Count++;
                        }
                        currentNode = currentNode.Children[c - 'a'];
                    }
                }
                else if (q[0] == "find")
                {
                   
                    Node currentNode = root;
                    int count = 0;
                    int depth = 1;
                    foreach (char c in q[1])
                    {                    
                        if (currentNode.Children[c - 'a'] == null)
                            break;                 
                        if (q[1].Length == depth)
                            count = currentNode.Children[c - 'a'].Count;
                        depth++;     
                        
                        currentNode = currentNode.Children[c - 'a'];               
                    }
                                    
                    counts.Add(count);
                }                
            }
    
        return counts;
    }
    

    }

  • + 0 comments

    This is my solution for Python 3.5+ using dictionaries.

    def contacts(queries):
        arr = defaultdict(list)
        r = []
        
        def find(word):
            index = word[0]
            l = len(word)
            r = 0
            
            for v in arr[index]:
                if v[:l] == word:
                    r +=1
            return r
            
        for q in queries:
            op, v = q
            
            if op == 'add':
                arr[v[0]].append(v)
            elif op == 'find':
                r.append(find(v))
        return r
    
  • + 0 comments

    Simple java code using Trie -

    class TrieNode{ TrieNode[] children = new TrieNode[26]; int we,prefix; public TrieNode(){ we=0; prefix=0; for(int i=0;i<26;i++) children[i]=null; } }

    class Result {

        public static TrieNode root = new TrieNode();
        static int c=0;
    
        public static void Insert(String s){
           TrieNode copy=root;
           for(int i=0;i<s.length();i++){
                   int ch=s.charAt(i)-'a';
                   if(copy.children[ch]==null)
                   copy.children[ch]=new TrieNode();
                   copy=copy.children[ch];
                   copy.prefix++;
           }
           copy.we++;
           return;
        }
    
        public static int Search(String s){
                TrieNode copy=root;
                for(int i=0;i<s.length();i++){
                        int ch=s.charAt(i)-'a';
                        if(copy.children[ch]==null)
                        return 0;
                         copy=copy.children[ch];
                }
                c=copy.prefix;
                return c;
        }
    
    public static List<Integer> contacts(List<List<String>> queries) {
    // Write your code here
    List<Integer> l=new ArrayList<Integer>();
    for(List<String> i: queries){
    if(i.get(0).equals("add"))
    Insert(i.get(1));
    else{
            c=0;
    int count = Search(i.get(1));
    l.add(count);
    }
    }
    return l;
    

    } }

  • + 0 comments
    case class TrieNode(var count: Int = 0,
      val children: Map[Char, TrieNode] = Map.empty) {}
    
    class Trie {
        private val root = new TrieNode()
    
      def add(word: String) = 
        word.foldLeft(root) { case (depth,char) => {
          depth.children
            .getOrElseUpdate(char, new TrieNode())
            .tap(_.count += 1)}}
    
      def find(prefix: String): Int = 
        prefix.foldLeft(Option(root)) { (traverse, char) =>
          traverse.flatMap(_.children.get(char))} match {
            case Some(node) => node.count
            case None => 0 }
            
     }
    
    def contacts ( queries: Array[Array[String]]): Array[Int] = {
      queries.foldLeft((new Trie(), ListBuffer.empty[Int])) {
        case ((trie,res),q) => q match {
          case Array("add",w) => trie.add(w)
            (trie,res)
          case Array("find",w) => 
            (trie,res.append(trie.find(w)))
      }}._2.toArray
    }
    
  • + 0 comments
    I implemented my code using Trie with array of size 26 but only 2 test cases are passed. Can anyone help?
    
    class TrieNode{
    public:
    char data;
    TrieNode **children;
    bool isTerminal;
    
    TrieNode(char data){
        this->data = data;
        children = new TrieNode*[26];
    
        for(int i = 0; i < 26; i++){
            children[i] = NULL;
        }
    
        isTerminal = false;
    }
    

    };

    class Trie{ TrieNode *root;

    public:
    Trie(){
        root = new TrieNode('\0');
    }
    
    void add(TrieNode *root, string word){
        if(word.size() == 0){
            root->isTerminal = true;
            return;
        }
    
        int index = word[0] - 'a';
        TrieNode *child;
    
        if(root->children[index] != NULL){
            child = root->children[index];
        }
        else{
            child = new TrieNode(word[0]);
            root->children[index] = child;
            // cout<<root->children[index]->data<<endl;
        }
    
        add(child, word.substr(1));
    }
    
    void add(string word){
        add(root, word);
    }
    
    int find(TrieNode *root, string word){
    
        if(word.size() == 0){
            int counter = 1;
    
            for(int i = 0; i < 26; i++){
                if(root->children[i] != NULL){
                    counter++;
                }
            }
            return counter;
        }
    
        int index = word[0] - 'a';
    
        if(root->children[index] != NULL){
            TrieNode *child = root->children[index];
            return find(child, word.substr(1));
        }
        else{
            return 0;
        }
    
    }
    
    int find(string word){
        return find(root, word);
    }
    

    };

    vector contacts(vector> queries) { vector result; Trie *trie = new Trie();

    for (int i=0; i < queries.size(); i++) {
    
        if (queries[i][0] == "add") {
            trie->add(queries[i][1]);
        }
        else if(queries[i][0] == "find") {
            result.push_back(trie->find(queries[i][1]));
        }
    }
    
    return result;
    

    }