No Prefix Set

  • + 1 comment

    Java 8 version (not type-safe(?)) simplified and updated thanks to @dgzwiro !

    public static final char END = '_';
    public static final String BAD_SET_FORMAT = "BAD SET\n%s";
    
    public static void noPrefix(List<String> words) {
    // Write your code here
        Map<Character, Object> trie = new HashMap<>();
        Map<Character, Object> current = null;
        // incremental insertion of words
        for (String word: words) {
            current = trie;
            // for each word, insert and change current map/dict per letter
            for (char c: word.toCharArray()) {
                // FAIL: a processed word is the prefix of the current word
                if (current.containsKey(END)) {
                    System.out.printf(BAD_SET_FORMAT, word);
                    return;
                }
                // create map/dict if missing
                if (!current.containsKey(c)) {
                    current.put(c, new HashMap<Character, Object>());
                }
                current = (HashMap<Character, Object>) current.get(c);
            }
            
            // FAIL: current word map/dict is not empty
            // meaning either:
            // - current word was already inserted in the trie
            // - current word was a prefix of previously inserted words
            if (!current.isEmpty()) {
                System.out.printf(BAD_SET_FORMAT, word);
                return;
            }
            
            // mark the current node where the current word ends here
            current.put(END, null);
        }
        System.out.println("GOOD SET");
    }