Amazon Customer Reviews Question
Anonymous User
18447

Amazon Customer Review Question for Practice from Amazon Career Day
image

Here is my Code, fails at some cases, can't figure out why
Can someone help?

static class TrieNode{

        HashMap<Character, TrieNode> child;
        List<String> list;
        boolean isWord;

        public TrieNode(){
            child = new HashMap<>();
            list = new ArrayList<>();
        }
    }
    public static List<List<String>> searchSuggestions(List<String> repository, String customerQuery) {
    List<List<String>> res = new ArrayList<>();
    Collections.sort(repository);
    TrieNode root = buildTree(repository);
    TrieNode curr = root;
    boolean flag = false;
    for (int i=0; i<customerQuery.length(); i++){
        char key = customerQuery.charAt(i);
        curr = curr.child.get(key);
        if (curr == null){
            flag = true;
            break;
        }
        if (i > 0){
            List<String> temp = new ArrayList<>();
			List<String> words = curr.list;
			for (int j=0; j<3 && j < words.size(); j++)
				temp.add(words.get(j).toLowerCase());
            res.add(temp);
        }
    }
    return res;
    }

    public static TrieNode buildTree(List<String> repository){
        TrieNode root = new TrieNode();
        for (String s : repository){
            TrieNode curr = root;
            for (int i=0; i<s.length(); i++){
                char key = s.charAt(i);
                if (curr.child.get(key) == null){
                    curr.child.put(key, new TrieNode());
                }
                curr = curr.child.get(key);
                curr.list.add(s);
            }
            curr.isWord = true;
        }
        return root;
    }
Comments (18)