No Prefix Set

  • + 0 comments

    Optionally, no need for a trie here.

    To keep it simple, just use a BST and make a second pass through the list. Example in Java 17:

        /**
         * Find the first string within a list which creates a prefix
         * relationship with any other string. 
         *
         * Applies a sorted map. Reporting the first occurrence is
         * rather troublesome: This requires tracking the index of
         * each prefix relationship and making a second pass.
         *
         * 𝚯(N log N)
         * 𝚯(N) space (red-black tree)
         *
         * https://github.com/profinite/HackerRank/
         */
        public static void noPrefix(List<String> words) {
           TreeMap<String, Integer> sorted = new TreeMap<>();
           int min = Integer.MAX_VALUE; // index of first observable prefix
           int index = 0;
           for (String word : words) {
                if (sorted.containsKey(word)) // check for identical
                    min = Math.min(min, index);
                sorted.putIfAbsent(word, index++); // sort the strings
            }
            for (String word : words.stream().distinct().toList()) {
                String next = sorted.higherKey(word);
                while (isPrefix(word, next)) {
                    min = Math.min(min, Math.max(sorted.get(word), sorted.get(next)));
                    next = sorted.higherKey(next);
                }
            }
            if(min != Integer.MAX_VALUE)
                System.out.println("BAD SET\n" + words.get(min));
            else
                System.out.println("GOOD SET");
        }
        static boolean isPrefix(String pre, String full) {
            return pre != null && full != null && full.startsWith(pre);
        }