Getting everything ready for you…

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

0s

Practice › Trie

Replace Words with Roots

Medium · Trie · Asked at Amazon, Uber, Microsoft

A dictionary holds word roots. In the sentence, replace every word that starts with some root by the shortest such root. Words that start with no root stay unchanged. Print the new sentence.

Input

First line: n. Second line: the n roots. Third line: the sentence (words separated by single spaces).

Output

The sentence after replacement.

Constraints

Insert the roots into a trie. For each word, walk down the trie letter by letter; the first node that ends a root gives the shortest root. If the walk falls off the trie, keep the word.

Example 1

Input

3
cat bat rat
the cattle was rattled by the battery

Output

the cat was rat by the bat

Example 2

Input

3
a b c
aadsfasf absbs bbab cadsfafs

Output

a a b c

Hints

  1. Put the roots in a trie and mark the nodes where a root ends.
  2. For a word, follow its letters down the trie.
  3. The first marked node you meet is the shortest root.

Approach

Insert every root. For each word of the sentence walk the trie: if a node on the way ends a root, output the letters walked so far; if the next letter is missing, the word has no root — output it unchanged. Each word costs at most its length (or the longest root, whichever is smaller).

Complexity: O(total letters) time · O(letters in the roots) 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<array<int, 26>> nxt(1);
    vector<bool> isEnd(1, false);
    nxt[0].fill(-1);
    for (int i = 0; i < n; i++) {
        string root;
        cin >> root;
        int cur = 0;
        for (char c : root) {
            int x = c - 'a';
            if (nxt[cur][x] == -1) {
                nxt[cur][x] = nxt.size();
                nxt.emplace_back();
                nxt.back().fill(-1);
                isEnd.push_back(false);
            }
            cur = nxt[cur][x];
        }
        isEnd[cur] = true;
    }
    string word, out;
    while (cin >> word) {
        int cur = 0;
        string res = word;
        for (int i = 0; i < (int) word.size(); i++) {
            cur = nxt[cur][word[i] - 'a'];
            if (cur == -1) break;
            if (isEnd[cur]) {
                res = word.substr(0, i + 1);
                break;
            }
        }
        if (!out.empty()) out += ' ';
        out += res;
    }
    cout << out << "\n";
    return 0;
}

Python solution

import sys

lines = sys.stdin.read().split("\n")
roots = lines[1].split()
END = "#"
trie = {}
for root in roots:
    node = trie
    for c in root:
        node = node.setdefault(c, {})
    node[END] = True


def replace(word):
    node = trie
    for i, c in enumerate(word):
        node = node.get(c)
        if node is None:
            return word
        if END in node:
            return word[: i + 1]
    return word


print(" ".join(replace(w) for w in lines[2].split()))

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));
        br.readLine();
        String[] roots = br.readLine().trim().split("\\s+");
        List<int[]> nxt = new ArrayList<>();
        List<Boolean> isEnd = new ArrayList<>();
        int[] rootNode = new int[26];
        Arrays.fill(rootNode, -1);
        nxt.add(rootNode);
        isEnd.add(false);
        for (String root : roots) {
            int cur = 0;
            for (char c : root.toCharArray()) {
                int x = c - 'a';
                if (nxt.get(cur)[x] == -1) {
                    int[] fresh = new int[26];
                    Arrays.fill(fresh, -1);
                    nxt.add(fresh);
                    isEnd.add(false);
                    nxt.get(cur)[x] = nxt.size() - 1;
                }
                cur = nxt.get(cur)[x];
            }
            isEnd.set(cur, true);
        }
        StringBuilder sb = new StringBuilder();
        for (String word : br.readLine().trim().split("\\s+")) {
            int cur = 0;
            String res = word;
            for (int i = 0; i < word.length(); i++) {
                cur = nxt.get(cur)[word.charAt(i) - 'a'];
                if (cur == -1) break;
                if (isEnd.get(cur)) {
                    res = word.substring(0, i + 1);
                    break;
                }
            }
            if (sb.length() > 0) sb.append(' ');
            sb.append(res);
        }
        System.out.println(sb);
    }
}

Solve Replace Words with Roots online · All practice problems