Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Trie

Shortest Unique Prefix

Medium · Trie · Asked at Google, Amazon, Microsoft

For each word, print its shortest prefix that is not a prefix of any other word in the list. No word is a prefix of another, so such a prefix always exists.

Input

First line: n. Next n lines: one word each (all distinct).

Output

n lines — the shortest unique prefix of each word, in input order.

Constraints

Insert all words into a trie and count, at each node, how many words pass through it. For a word, walk down until the count is 1 — the letters walked so far are the answer.

Example 1

Input

4
zebra
dog
duck
dove

Output

z
dog
du
dov

Example 2

Input

1
apple

Output

a

Hints

  1. A prefix is unique when exactly one word in the list starts with it.
  2. In a trie, count how many words pass through each node.
  3. For each word, stop at the first node on its path whose count is 1.

Approach

Insert all words, incrementing a counter on every node along each path. Then, for each word, walk down its letters; the first node with count 1 means no other word shares this prefix, so the letters walked so far are the answer. Because no word is a prefix of another, every word reaches such a node before it ends.

Complexity: O(total letters) time and space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<string> w(n);
    for (auto &s : w) cin >> s;
    vector<array<int, 26>> nxt(1);
    nxt[0].fill(-1);
    vector<int> cnt(1, 0);
    for (auto &s : w) {
        int cur = 0;
        for (char c : s) {
            int x = c - 'a';
            if (nxt[cur][x] == -1) {
                nxt[cur][x] = nxt.size();
                nxt.emplace_back();
                nxt.back().fill(-1);
                cnt.push_back(0);
            }
            cur = nxt[cur][x];
            cnt[cur]++;
        }
    }
    for (auto &s : w) {
        int cur = 0, len = 0;
        for (char c : s) {
            cur = nxt[cur][c - 'a'];
            len++;
            if (cnt[cur] == 1) break;
        }
        cout << s.substr(0, len) << "\n";
    }
    return 0;
}

Python solution

import sys

data = sys.stdin.read().split()
n = int(data[0])
words = data[1 : 1 + n]
trie = {}
for w in words:
    node = trie
    for c in w:
        node = node.setdefault(c, {"#": 0})
        node["#"] += 1
out = []
for w in words:
    node, length = trie, 0
    for c in w:
        node = node[c]
        length += 1
        if node["#"] == 1:
            break
    out.append(w[:length])
print("\n".join(out))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine().trim());
        String[] w = new String[n];
        for (int i = 0; i < n; i++) w[i] = br.readLine().trim();
        List<int[]> nxt = new ArrayList<>();
        List<Integer> cnt = new ArrayList<>();
        int[] root = new int[26];
        Arrays.fill(root, -1);
        nxt.add(root);
        cnt.add(0);
        for (String s : w) {
            int cur = 0;
            for (char c : s.toCharArray()) {
                int x = c - 'a';
                if (nxt.get(cur)[x] == -1) {
                    int[] fresh = new int[26];
                    Arrays.fill(fresh, -1);
                    nxt.add(fresh);
                    cnt.add(0);
                    nxt.get(cur)[x] = nxt.size() - 1;
                }
                cur = nxt.get(cur)[x];
                cnt.set(cur, cnt.get(cur) + 1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String s : w) {
            int cur = 0, len = 0;
            for (char c : s.toCharArray()) {
                cur = nxt.get(cur)[c - 'a'];
                len++;
                if (cnt.get(cur) == 1) break;
            }
            sb.append(s, 0, len).append('\n');
        }
        System.out.print(sb);
    }
}

Solve Shortest Unique Prefix online · All practice problems