Tries: Contacts

Sort by

recency

|

507 Discussions

|

  • + 0 comments

    Property issues can get stressful when answers aren’t clear. Speaking with a Real Estate Lawyer made it easier to understand what needed to be done and why each step mattered. The guidance helped avoid delays and confusion during the process. It felt reassuring to have support focused on solving real problems, not just paperwork.

  • + 0 comments
    from collections import defaultdict
    if __name__ == '__main__':
        n = int(input().strip())
        _map=defaultdict(int)
        for n_itr in range(n):
            first_multiple_input = input().rstrip().split()
            op = first_multiple_input[0]
            contact = first_multiple_input[1]
            if op=='add':
                if len(contact)>0:
                    for i in range(len(contact)+1): 
                        _map[contact[:i]]+=1 
            else:
                print(_map.get(contact, 0))
    
  • + 1 comment

    import java.io.; import java.math.; import java.security.; import java.text.; import java.util.; import java.util.concurrent.; import java.util.regex.*;

    public class Solution {

    private static final Scanner scanner = new Scanner(System.in);
    
    private static ArrayList<HashSet<String>> InitializeContactArray(){
    
        ArrayList<HashSet<String>> contactArray = new ArrayList<HashSet<String>>();
    
        for(int i=0;i<26;i++){
            contactArray.add(new HashSet<String>());
        }
    
        return contactArray;
    }
    
    private static int GetFirstCharacterIndex(String contact){
        return contact.charAt(0) - 97;
    }
    
    public static void main(String[] args) {
        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
    
        ArrayList<HashSet<String>> contactArray = InitializeContactArray();
    
        for (int nItr = 0; nItr < n; nItr++) {
            String[] opContact = scanner.nextLine().split(" ");
    
            String operation = opContact[0];
            String contact = opContact[1];
            Integer index = GetFirstCharacterIndex(contact);
            HashSet<String> contactSet = contactArray.get(index);
    
            if(operation.equals("add")){
                contactSet.add(contact);
            }
            else{
    
                Integer matches = 0;
    
                for (String contactName : contactSet) {
                    if(contactName.startsWith(contact)){
                        matches++;
                    }
                }
    
                System.out.println(matches);
            }
    
        }
    
        scanner.close();
    }
    

    }

  • + 0 comments

    Working Python recursive OOP implementation of Trie. Storing the size rather than computing recursively is essential to pass the tests.

    class PrefixTree():
        
        def __init__(self, is_end=False):
            self.d = dict()
            self.is_end = is_end
            self.size = 0
        
        # Recursively add character by character
        def add(self, word):
            # Base case: empty or existing word
            if len(word) == 0 or self.find(word):
                return -1
            if word[0] not in self.d.keys():
                self.d[word[0]] = PrefixTree()
            # Base case: one character word
            if len(word) == 1:
                self.d[word[0]].is_end = True
            # Recursive case: add the remaining characters
            else:
                self.d[word[0]].add(word[1:])
            # Caching the size is the key to good runtime in 'find()'
            self.size += 1
        
        # Returns number of matches for a prefix
        def find(self, prefix):
            # Base case: we're at the end node of the prefix
            if len(prefix) == 0:
                return self.size + (1 if self.is_end else 0)
            # Base case: we can't reach the next character
            if prefix[0] not in self.d.keys():
                return 0
            # Recursive case: keep looking
            return self.d[prefix[0]].find(prefix[1:])
    
  • + 0 comments

    Simple Ruby Trie OOP solution:

    class Contacts
      def initialize
        @root = ContactNode.new
      end
    
      def add(name)
        node = @root
        name.each_char do |c|
          idx = c2i(c)
          node.children[idx] = ContactNode.new if node.children[idx].nil?
          node = node.children[idx]
          node.count += 1
        end
      end
    
      def find_count(partial)
        node = @root
        partial.each_char do |c|
          idx = c2i(c)
          return 0 if node.children[idx].nil?
    
          node = node.children[idx]
        end
        node.count
      end
    
      private
    
      def c2i(c)
        c.ord - 'a'.ord
      end
    end
    
    class ContactNode
      attr_accessor :count, :children
    
      def initialize(alphasize = 26)
        @count = 0
        @children = Array.new(alphasize)
      end
    end
    
    contacts = Contacts.new
    gets.to_i.times do
      op, arg = gets.split
      case op
      when 'add'
        contacts.add(arg)
      when 'find'
        puts contacts.find_count(arg)
      end
    end