Practice › Trie
Concatenated Words
Hard · Trie · Asked at Amazon, Google, Apple
A word is a concatenated word if it can be written entirely as two or more (not necessarily different) shorter words from the same list. Print every concatenated word in the order of the input, one per line, or NONE if there is none.
Input
First line: n. Next n lines: one word each (all distinct).
Output
The concatenated words, one per line, or NONE.
Constraints
- 1 ≤ n ≤ 10^4
- 1 ≤ word length ≤ 30
- only lowercase letters
Process words from shortest to longest. A word is concatenated if a word-break DP over it succeeds using only the words already added (all shorter). Store the added words in a trie (or a hash set) so each DP step can walk forward letter by letter.
Example 1
Input
8 cat cats catsdogcats dog dogcatsdog hippopotamuses rat ratcatdogcat
Output
catsdogcats dogcatsdog ratcatdogcat
Example 2
Input
3 cat dog bird
Output
NONE
Hints
- The pieces of a concatenated word are shorter than it, so handle words from shortest to longest.
- For one word, a word-break DP asks: can the prefix of length i be split into known words?
- Walk a trie of the known words from each reachable split point to find all the pieces that start there.
Approach
Sort by length. For each word, run a DP where ok[i] means the first i letters can be split into words already in the trie; from every i with ok[i], walk the trie along the word and mark ok[j] wherever a stored word ends. If ok[len] is true (and at least one word was stored before), the word is concatenated — it needs two or more pieces automatically, because a single piece would have to be the word itself, which is not in the trie yet. Then insert the word. Print the concatenated words in input order.
Complexity: O(Σ len²) time · O(total letters) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
vector<array<int, 26>> nxt(1);
vector<bool> isEnd(1, false);
void insertWord(const string &s) {
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);
isEnd.push_back(false);
}
cur = nxt[cur][x];
}
isEnd[cur] = true;
}
bool canBuild(const string &s) {
int L = s.size();
vector<bool> ok(L + 1, false);
ok[0] = true;
for (int i = 0; i < L; i++) {
if (!ok[i]) continue;
int cur = 0;
for (int j = i; j < L; j++) {
cur = nxt[cur][s[j] - 'a'];
if (cur == -1) break;
if (isEnd[cur]) ok[j + 1] = true;
}
}
return ok[L];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
nxt[0].fill(-1);
int n;
cin >> n;
vector<string> w(n);
for (auto &s : w) cin >> s;
vector<int> order(n);
iota(order.begin(), order.end(), 0);
stable_sort(order.begin(), order.end(), [&](int a, int b) { return w[a].size() < w[b].size(); });
vector<bool> good(n, false);
for (int idx : order) {
if (nxt.size() > 1 && canBuild(w[idx])) good[idx] = true;
insertWord(w[idx]);
}
bool any = false;
for (int i = 0; i < n; i++)
if (good[i]) {
cout << w[i] << "\n";
any = true;
}
if (!any) cout << "NONE\n";
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
words = data[1 : 1 + n]
END = "#"
trie = {}
def can_build(s):
ok = [False] * (len(s) + 1)
ok[0] = True
for i in range(len(s)):
if not ok[i]:
continue
node = trie
for j in range(i, len(s)):
node = node.get(s[j])
if node is None:
break
if END in node:
ok[j + 1] = True
return ok[len(s)]
good = set()
for w in sorted(words, key=len):
if trie and can_build(w):
good.add(w)
node = trie
for c in w:
node = node.setdefault(c, {})
node[END] = True
res = [w for w in words if w in good]
print("\n".join(res) if res else "NONE")Java solution
import java.io.*;
import java.util.*;
public class Main {
static List<int[]> nxt = new ArrayList<>();
static List<Boolean> isEnd = new ArrayList<>();
static int newNode() {
int[] a = new int[26];
Arrays.fill(a, -1);
nxt.add(a);
isEnd.add(false);
return nxt.size() - 1;
}
static boolean canBuild(String s) {
int L = s.length();
boolean[] ok = new boolean[L + 1];
ok[0] = true;
for (int i = 0; i < L; i++) {
if (!ok[i]) continue;
int cur = 0;
for (int j = i; j < L; j++) {
cur = nxt.get(cur)[s.charAt(j) - 'a'];
if (cur == -1) break;
if (isEnd.get(cur)) ok[j + 1] = true;
}
}
return ok[L];
}
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();
newNode();
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> w[a].length() - w[b].length());
boolean[] good = new boolean[n];
for (int idx : order) {
if (nxt.size() > 1 && canBuild(w[idx])) good[idx] = true;
int cur = 0;
for (char c : w[idx].toCharArray()) {
int x = c - 'a';
if (nxt.get(cur)[x] == -1) {
int id = newNode();
nxt.get(cur)[x] = id;
}
cur = nxt.get(cur)[x];
}
isEnd.set(cur, true);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) if (good[i]) sb.append(w[i]).append('\n');
System.out.print(sb.length() == 0 ? "NONE\n" : sb);
}
}