No Prefix Set

  • + 0 comments

    Essentially you are looking for an overlap of any letter with the end of any word, so most of the code is just implementing a Trie, which is missing in Java

    public static void noPrefix(List<String> words) {
            //Sorting would make this faster, but their examples show we would reach the wrong result if sorted
            
            Trie trie = new Trie();
            for (String word : words) {
                //System.out.println("Add " + word + " to trie of size " + trie.size());
                if (trie.add(word)) {
                    //overlap detected
                    System.out.println("BAD SET");
                    System.out.println(word);
                    return;
                }
            }
            
             System.out.println("GOOD SET");
            
        }
        
        static class Trie extends HashMap<Character, TrieNode> {
                   
            /* returns true if an overlap is detected */       
            public boolean add(String word) {
                char c = word.charAt(0);
                TrieNode n = get(c);
                if (n == null) {
                    //System.out.println("=> Adding " + c + (word.length() == 1? " (Word End)":" (Node)"));
                    n = new TrieNode(word);
                    put(c,n);
                    return false; //its a new node it cant be an overlap
                } else {
                    //System.out.println("=> Updating " + c);
                    //We already have the first char as n, so just try the rest
                    if (word.length() > 1) { 
                        return n.add(word.substring(1));
                    } else {
                        n.isWordEnd = true; //its a word end now since we reached finalletter of a word
                    }
                }
                return n.isWordEnd;
            }
            
        }
        
        static class TrieNode {
            
            boolean isWordEnd = false;
            Trie branch = null;
            char c;
            
            public TrieNode(char c, boolean isWordEnd) {
                this.c = c;
                this.isWordEnd = isWordEnd;
            }
            
            public TrieNode(String c) {
                this(c.charAt(0), c.length() == 1);
                if (c.length() > 1) {
                    add(c.substring(1));
                }
            }
            
            /* method assumes, this is letters after c, that c is already trimmed */
            /* returns true if an overlap is detected */   
            public boolean add(String word) {
                if (branch == null) {
                    branch = new Trie();
                } 
                //System.out.println("=> Add " + word.charAt(0) + " after " + c);
                return isWordEnd || branch.add(word);
            }
                   
        }