Find shortest unique prefix for every word in a given list

Pattern: Insert, search and prefix

medium

Insert every word, counting at each node how many words pass through it. A word's shortest unique prefix ends at the first node on its path that only one word passes through.

The problem

Given words where none is a prefix of another, return for each word (in order) its shortest prefix that is not a prefix of any other word.

Think first

  • What does 'unique' mean for a prefix?
  • What does a pass count tell you?
  • Why does the 'no word is a prefix of another' rule matter?

Hints

    Brute force, and why it fails

    For each word and each prefix length, check every other word: O(n² × L²).

    The key insight

    Pass counts are filled once; then each word's answer is the first node with count 1 on its own path.

    Dry run

    zebra, dog, duck, dove. z is used by one word: z.

    Step 1 of 2

    The plan

    insert every word, pass += 1 along the path
    for each word: walk until a node has pass 1; the prefix so far is the answer
    

    Complexity

    Time
    O(total letters)
    Space
    O(total letters)

    Two walks per word.

    Edge cases

    • One word: its first letter.
    • Words differing only at the end.
    • Single-letter words.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private static class Node {
            Node[] next = new Node[26];
            int pass;                               // how many words go through this node
        }
    
        public List<String> findPrefixes(String[] arr) {
            Node root = new Node();
            for (String w : arr) {                  // count, for every prefix, how many words share it
                Node n = root;
                for (char c : w.toCharArray()) {
                    if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
                    n = n.next[c - 'a'];
                    n.pass++;
                }
            }
            List<String> out = new ArrayList<>();
            for (String w : arr) {
                Node n = root;
                int len = 0;
                while (len < w.length()) {          // stop at the first prefix no other word shares
                    n = n.next[w.charAt(len) - 'a'];
                    len++;
                    if (n.pass == 1) break;
                }
                out.add(w.substring(0, len));
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<string> findPrefixes(vector<string>& arr) {
            vector<vector<int>> next{vector<int>(26, 0)};   // next[node][letter], 0 = none
            vector<int> pass{0};                    // how many words go through each node
            for (const string& w : arr) {           // count, for every prefix, how many words share it
                int n = 0;
                for (char c : w) {
                    if (next[n][c - 'a'] == 0) {
                        next[n][c - 'a'] = static_cast<int>(next.size());
                        next.push_back(vector<int>(26, 0));
                        pass.push_back(0);
                    }
                    n = next[n][c - 'a'];
                    pass[n]++;
                }
            }
            vector<string> out;
            for (const string& w : arr) {
                int n = 0;
                size_t len = 0;
                while (len < w.size()) {            // stop at the first prefix no other word shares
                    n = next[n][w[len] - 'a'];
                    len++;
                    if (pass[n] == 1) break;
                }
                out.push_back(w.substr(0, len));
            }
            return out;
        }
    };

    Python

    class Solution:
        def findPrefixes(self, arr: list[str]) -> list[str]:
            root = {}
            for w in arr:                           # count, for every prefix, how many words share it
                node = root
                for c in w:
                    node = node.setdefault(c, {"#": 0})
                    node["#"] += 1
            out = []
            for w in arr:
                node, length = root, 0
                while length < len(w):              # stop at the first prefix no other word shares
                    node = node[w[length]]
                    length += 1
                    if node["#"] == 1:
                        break
                out.append(w[:length])
            return out

    Common mistakes

    • Stopping one letter too early.
    • Counting at the root.

    Similar problems