We are given n strings, each consisting of distinct small letters, and each string is non-empty. The genome we need to construct is a string of distinct letters (each letter at most once). It must contain each given fragment as a substring (contiguous sequence). The input guarantees existence. Among all possible such strings with distinct letters, we need one with minimum length. If multiple, any.
Observations: Since the genome has distinct letters, it's essentially a permutation of some subset of letters (each appears at most once). The constraints: each fragment is a string of distinct letters, and must appear as a contiguous substring in the genome. Also, fragments may overlap, be substrings of each other.
Goal: find shortest string of distinct letters that contains all fragments as substrings.
This is reminiscent of constructing a superstring from a set of strings with constraints that letters are distinct. But because the letters are distinct across the whole genome, it's a special case: each letter appears only once. So the genome is a string where each character is unique. So it's essentially an ordering of a set of letters. The fragments are substrings, meaning they impose constraints on the relative order of letters: for a fragment "abc", the genome must have a contiguous block where a, b, c appear consecutively in that order. Since letters are distinct, this means that a must be immediately followed by b, and b immediately followed by c. Actually substring means contiguous sequence, so "abc" must appear exactly as a, then b, then c consecutively. So it's a constraint that a, b, c appear consecutively in that order.
But wait: could there be other letters interleaved? No, because substring means contiguous, so if the fragment is "ab", the genome must contain "ab" as a substring, meaning there is some position i such that genome[i] = 'a' and genome[i+1] = 'b'. So the letters a and b must be adjacent (with a before b) somewhere. For "abc", a must be adjacent to b, and b adjacent to c, and also they must be in order: a then b then c consecutively. So that implies a is immediately followed by b, and b immediately followed by c. So these are constraints on consecutive pairs.
However, there is nuance: If fragment is longer, it imposes constraints on a chain of consecutive adjacencies.
But could the fragment appear multiple times? Possibly if genome has distinct letters, each letter appears once, so the fragment can appear at most once (since the substring uses letters in order, and they are unique, it can't appear overlapping in different ways). Actually it could appear in different positions if the letters are repeated? But they are distinct, so no. So each fragment corresponds to a unique occurrence (the letters are distinct). So it's a constraint that the letters in the fragment appear consecutively in that order.
Therefore, the problem reduces to: We have letters (the union of all letters appearing in fragments). We need to order them (a permutation) such that for each fragment, its letters appear as a contiguous block in that order. Additionally, the genome must contain only letters that appear in fragments? Probably yes, but could also contain extra letters? The genome can contain any distinct letters, not necessarily only those from fragments. But if we add extra letters, the length increases, and we want minimal length, so we probably do not want any extra letters unless necessary to satisfy constraints? However, constraints may require inclusion of letters not in any fragment? For example, if fragments are "ab" and "bc", the genome must contain ab as substring and bc as substring. With distinct letters, to have both, we need the string "abc"? Let's see: "abc" contains "ab" (positions 1-2) and "bc" (positions 2-3). So union letters: a,b,c. So we don't need extra. But if fragments are "ab" and "cd", we could have "abcd", containing both substrings? "ab" appears at start, "cd" at end. So union letters suffice. What about fragments "ab" and "ba"? But fragments have distinct letters, so "ba" also distinct letters, but they can't both be substrings of a string with distinct letters? Actually consider string "aba"? Not allowed because 'a' repeated. So impossible. But input guarantees existence. So no conflicting fragments. So we likely only need to include letters from fragments. Could adding extra letters ever allow a shorter genome? Adding extra letters increases length, so no. So minimal length genome will be exactly the set of all letters that appear in any fragment? Possibly yes, but need to ensure that all fragments appear as substrings. Since each fragment uses letters from that set, if we include all letters, we have to order them to satisfy contiguity constraints. It's possible that we need to include some letters that are not in any fragment to make constraints work? Suppose fragments are "ab" and "bc". The union is a,b,c, ordering abc works. Suppose fragments are "ab" and "ac"? But "ac" has distinct letters, but to have both "ab" and "ac" as substrings in a string of distinct letters, is it possible? Let's test: We need a followed by b (adjacent) somewhere, and a followed by c (adjacent) somewhere. Since 'a' appears only once, it can have only one immediate successor. So impossible. So input would not have such fragments because guaranteed existence. So indeed constraints must be consistent. So union letters suffice.
Thus, we need to find a permutation of all letters appearing in fragments such that each fragment's letters appear consecutively in that order. Additionally, because fragments might overlap, they might impose constraints that certain letters must be adjacent or certain orderings of blocks.
This is akin to constructing a string from given substrings with unique characters, which essentially builds a directed graph of adjacency constraints: For each fragment, for each consecutive pair (s[i], s[i+1]), we require that s[i] is immediately followed by s[i+1] in the genome. Since letters are unique, that means that the successor of s[i] must be s[i+1]. So each letter can have at most one outgoing "must-follow" edge (since if a letter appears in multiple fragments, it might be required to be followed by different letters, causing conflict; but existence guarantee means no conflict). Similarly, each letter can have at most one incoming "must-precede" edge? Actually from constraints, if a fragment contains ... x y ..., then y must be immediately preceded by x (since x is before y and they are adjacent). So that gives an incoming edge to y from x. So each letter can have at most one predecessor and at most one successor if constraints are consistent. However, fragments may impose longer chains; but those can be decomposed into pairwise constraints.
But also there is contiguity: For fragment "abc", we also need that a, b, c appear consecutively, not just that a->b and b->c. But if we have a->b and b->c, then the triple a,b,c will be consecutive as long as there are no other letters between a and b or b and c. Since we enforce that the successor of a is b, that means immediately after a is b. And successor of b is c, so immediately after b is c. So indeed the triple is contiguous. So pairwise constraints suffice.
But what about overlapping fragments like "ab" and "bc" give a->b and b->c. That's fine.
What about fragments that impose ordering but not necessarily adjacency? Actually substring requires adjacency, so they all impose adjacency.
Thus, each fragment gives a chain of adjacency constraints: for i from 0 to len-2, s[i] must be immediately followed by s[i+1]; equivalently, s[i+1] must be immediately preceded by s[i].
Thus, we can model the genome as a set of letters, with some forced edges between letters indicating that one must directly follow the other. Since each letter appears at most once, the genome will be a sequence that can be seen as a set of chains (or a single chain) where some links are forced, and other letters can be placed arbitrarily relative to each other as long as they don't break forced adjacencies.
But there might be additional constraints: For example, fragment "abc" also implies that there is no other letter between a and c except b. If we have forced edges a->b and b->c, that is sufficient. However, could there be constraints that some letters must be adjacent even if not explicitly in a fragment? Possibly due to overlapping fragments: e.g., fragments "ab" and "abc"? Actually "abc" includes "ab" already, so fine. Fragments "ab" and "bc" give a->b and b->c, so they imply that a,b,c must appear consecutively in that order. That's the chain a->b->c. So they are combined into a longer forced chain.
But what about fragments that share letters but not in a simple chain? For example, fragments "ab" and "ac". That would require a's successor to be both b and c, impossible. So input avoids.
Thus, the constraints essentially define a set of directed edges such that the resulting graph is a collection of vertex-disjoint paths (each vertex has indegree ≤ 1, outdegree ≤ 1). Because each letter can have at most one forced predecessor (from any fragment) and at most one forced successor. And if there is a cycle, that would be impossible because distinct letters can't form a cycle? Actually a cycle would imply a->b, b->c, c->a, which would require a string like abc? But with distinct letters, a cycle would be possible if the string is cyclic? But we need a linear string. A cycle would force a to be followed by b, b by c, c by a. But in a linear string, a can't be both before and after c? Actually if we have a->b, b->c, c->a, that would require the sequence ... a,b,c,a,... but a repeats, impossible. So cycles are impossible. So the forced edges form a set of disjoint paths.
Now, besides forced edges, we have letters that are not constrained relative to each other. They can be placed anywhere as long as they don't break the forced chains. However, there may be constraints from fragments that are longer than 2, which already captured as chains; but also we need to ensure that the entire fragment appears as a substring, not just the pairwise adjacencies. Actually if we enforce all pairwise adjacencies of a fragment, the fragment appears as a contiguous block. So that's covered.
But what about fragments that impose that a block of letters appear contiguously, but the letters inside the block might have other forced edges that conflict? For example, suppose we have fragment "abc" and also fragment "bcd". Then we have edges a->b, b->c from first, and b->c, c->d from second. So edges consistent. The resulting chain is a->b->c->d. So the string must contain "abcd". Does that satisfy both fragments? "abc" appears as positions 1-3, "bcd" as 2-4. So yes.
Now, what about fragments that are not chains but impose that certain letters are adjacent in a specific order? Already done.
Thus, the problem reduces to: given a set of letters, and a set of constraints in the form of forced adjacency pairs (from fragments), we need to produce a string (permutation of all letters) that respects that each forced pair appears as consecutive in that order. Additionally, we must also respect that each fragment appears as a substring, but that is automatically satisfied if we include all forced adjacencies of the fragment? Actually if we have all pairwise adjacencies of a fragment, then the fragment appears as a contiguous block. But is it possible that the forced adjacencies from different fragments cause the fragment's letters to be separated by other letters in the middle? For example, consider fragment "abc". The forced adjacencies are a->b and b->c. If we have a->b, b->c as edges, then in the final sequence, a must be directly followed by b, and b directly followed by c. So the triple a,b,c will appear consecutively (a,b,c). So it's fine.
But what if a fragment has length 1? Then it imposes no adjacency constraints, just that the letter appears somewhere. Since all letters appear, it's satisfied.
So we can treat each fragment of length L as giving L-1 adjacency constraints.
Now, with these constraints, we need to construct a permutation of all letters that includes these adjacencies. This is essentially finding a Hamiltonian path (ordering) of all vertices (letters) that respects the forced edges (i.e., the edges must appear as consecutive in the order). Since the forced edges form disjoint paths, we can treat each path as a block that must appear consecutively in the order, and the blocks can be arranged arbitrarily.
Thus, the minimal length genome is simply the union of all letters. So we just need to output any ordering that respects forced adjacencies. However, is it always minimal to include all letters? Could we possibly omit some letter that appears in fragments? No, because each fragment must be a substring; if a letter appears in a fragment, it must be present in the genome. So we must include all letters from fragments. So minimal length = number of distinct letters across fragments.
But wait: Could there be a scenario where including all letters leads to a longer string than necessary because some letters might be redundant if they appear in fragments but the fragments could be satisfied by a superset? No, we must include each letter because it appears in some fragment. So yes.
Thus, the answer is simply a permutation of the distinct letters that satisfies adjacency constraints.
But is there any possibility that the forced edges from fragments might not cover all letters? Some letters might not have any forced predecessor/successor; they are isolated. Then they can be placed anywhere.
Thus, algorithm: Build a directed graph where edges represent that the first character must be immediately followed by the second. Also, we need to ensure consistency: each node has at most one outgoing edge and at most one incoming edge. Also, there should be no cycles. The input guarantees existence, but we may still need to detect for our construction.
Then, we need to output a string that is a concatenation of the forced chains, with the isolated letters inserted arbitrarily? But careful: If we have forced edges a->b and c->d, we could output "ab" + "cd" or "cd" + "ab" or maybe interleave? However, if we interleave like "a c b d", that would break adjacency a->b? Because a is followed by c, not b. So blocks must remain contiguous. So we must treat each maximal directed path (where each internal node has indegree=outdegree=1) as a block that must appear as a contiguous sequence in the order. The blocks can be arranged in any order. Also, nodes with indegree=0 and outdegree=0 are singletons that can be placed anywhere.
Thus, we can:
- Collect all letters from all fragments.
- Build adjacency map succ, pred.
- For each fragment string s, for i from 0 to len(s)-2:
if succ[s[i]] is already set and not equal to s[i+1], then conflict (but guarantee no conflict).
set succ[s[i]] = s[i+1], pred[s[i+1]] = s[i].
But we must be careful about overlapping constraints that are already implied; it's fine.
After building, we need to produce a string.
We must also consider that fragments might give constraints that are not simply captured by pairwise edges if there is a fragment that is longer and overlaps with other fragments in a way that creates a forced ordering but not necessarily adjacency? Actually no, only adjacency matters.
But is there any scenario where just having the pairwise constraints is insufficient? For instance, suppose we have fragments "ab" and "bc". The pairwise constraints give a->b, b->c. That yields "abc". Works. Suppose we have fragments "abc" and "b". The fragment "b" is length 1, no constraints. The forced edges from "abc" give a->b, b->c. That yields "abc". Works. Suppose we have fragments "ab" and "abc"? Actually "abc" gives a->b and b->c; "ab" gives a->b, which is consistent. So we get a->b, b->c. Fine.
Now, could there be a situation where a fragment imposes that three letters appear consecutively, but due to other constraints, the three letters might be forced to be consecutive but not in the exact order? Actually the fragment imposes order, so we need order.
Thus, pairwise edges suffice.
Now, what about fragments like "ab" and "cd"? Edges a->b, c->d. Then we can output "abcd" or "cdab". Both are fine.
Thus, the answer seems straightforward: we need to output any topological ordering? But not exactly topological, because there is no partial order beyond the forced adjacency chains; but we need to concatenate chains.
But is there any additional constraint from the fact that fragments must appear as substrings, and if we just concatenate chains arbitrarily, will each fragment indeed appear as a substring? For a fragment that is exactly a chain (or part of a chain), as long as the forced edges ensure the fragment's letters appear consecutively in the correct order, it will be a substring. But if the fragment spans across the boundary between two chains? Could that happen? For example, suppose we have fragment "ab" and also fragment "bc", which we already handled as a chain a->b->c. That's fine. But consider two fragments that are not merging into a single chain because they don't share letters? Then they are separate chains.
But what if a fragment is "abc" but the forced edges from fragments create two separate chains: a->b and c is somewhere else? That would be inconsistent because "abc" would require b->c as well. So if "abc" exists, we must have b->c edge; so c is in same chain.
Thus, all letters of a fragment must belong to a single chain? Possibly, but not necessarily. For a fragment of length L, its letters must appear consecutively. That implies that for each i, letter i and i+1 are consecutive in the genome. So the fragment's letters form a contiguous block, meaning they appear as a subpath in the genome. The genome's adjacency structure is a total order (a permutation). The contiguous block means that the letters appear consecutively in that total order. So if we consider the genome as a sequence, the fragment corresponds to a contiguous subsequence. In terms of forced edges, if we have edges a->b and b->c for "abc", that ensures a,b,c appear consecutively. But what about if the fragment is "ab" and "bc" separately, they force a->b and b->c, which merges them. So indeed all letters in a fragment are forced to be consecutive and in order.
Now, consider the scenario: we have fragments "ab" and "cd". These are separate blocks. The final genome could be "abcd". In that case, both fragments appear: "ab" at start, "cd" at end. But what if we arrange as "acbd"? Then "ab" is not a substring because a and b are not adjacent. So we must ensure that blocks stay contiguous.
Thus, our approach of building forced edges and then concatenating the resulting chains (maximal paths) in any order should yield a string where all forced edges hold, and thus all fragments are substrings. However, we need to ensure that when we concatenate chains, we don't accidentally create new adjacencies that break something? No, because only forced edges matter. But what about fragments that are exactly a chain? They will appear as substring within their chain. For fragments that are a subpath of a longer chain, they also appear. So fine.
But is it possible that some fragment is not a contiguous block even though all pairwise edges are satisfied? For example, suppose we have forced edges a->b and c->d. And we also have fragment "abc"? That would require b->c, which is missing, so not allowed. So with only these edges, "abc" cannot be satisfied. But we are given fragments; they impose edges, so we will have b->c if "abc" exists.
Thus, building edges from fragments ensures that fragment's adjacency constraints are included.
But wait: could there be a scenario where a fragment imposes that a block of letters appears contiguously, but the pairwise edges from that fragment might be satisfied, yet the block might be split due to other letters inserted inside the block? For example, we have forced edges a->b and b->c (from fragment "abc"). In the final genome, if we have a->b and b->c, then a,b,c are consecutive. But what if we also have an edge from b->x (from some other fragment)? That would conflict because b would have two successors (c and x). So not allowed. So b can have only one successor. So no other letter can be inserted between a and c because that would require either b's successor not be c, or something else between. Suppose we try to place something between a and b? That would break a->b because a's successor must be b. So it's forced. So indeed the block is contiguous.
Thus, the forced edges guarantee the block.
Therefore, constructing the string by concatenating maximal directed paths (chains) in any order yields a valid genome. But we must also incorporate isolated letters (no forced predecessor or successor) as singletons, which can be placed anywhere between chains or at ends.
Now, the question: Could there be a scenario where two chains have a letter in common? That would mean they merge, but if they share a letter, then they should be part of the same maximal chain, because forced edges would connect them. So we'll merge them.
Thus, algorithm steps:
-
Read n, then n strings.
-
Collect all distinct letters from all strings. Let's call set letters.
-
Initialize maps: succ = dict, pred = dict.
-
For each string s:
For i from 0 to len(s)-2:
a = s[i]; b = s[i+1];
If succ.get(a) is not None and succ[a] != b: conflict (but input guarantees none).
If pred.get(b) is not None and pred[b] != a: conflict.
Set succ[a]=b; pred[b]=a.
Additionally, we need to consider that the entire string must appear as contiguous block. Does setting pairwise edges guarantee that there are no extra letters inserted between non-consecutive positions of the fragment? Actually, if we have fragment "abc", pairwise edges guarantee a->b and b->c, so they are consecutive. That's enough.
However, there is a subtle case: fragments that are longer and contain repeated letters? But each fragment consists of distinct letters (given). So no repeats within a fragment.
-
After building edges, we must also ensure there are no cycles. The input guarantees existence, but we should still handle. If there is a cycle, then no linear order possible because each node would need to be followed by another, but then the cycle would require infinite distinct letters? Actually a cycle of length k would require that each node has a successor, but in a linear string, the last node has no successor, so cycle impossible. So the graph must be a set of disjoint paths.
-
Now we need to produce the genome as a string that includes all letters and respects the edges.
Approach: Find all nodes that have no predecessor (pred[v] is None). These are potential starting points of chains. For each such node, follow succ to build a chain: start = node, then while node in succ: append succ[node], move. That yields a string for that chain. Also, we need to include nodes that have both pred and succ? They will be covered in chains starting from nodes with no pred. But what about nodes that are isolated (no pred and no succ)? They are also starts, and chain length 1.
However, we must ensure we cover all letters. Nodes that have a pred but no pred entry? Actually all nodes with pred will be reached from some start by following succ, as long as there is no cycle. But if a node has pred but is not reachable from a start because of a cycle? Not possible if no cycles. So it's fine.
So we can collect all starts (nodes with no pred), for each follow succ to produce a string, and concatenate them in any order.
But is concatenating these chains in arbitrary order always valid? Let's check with an example: Suppose we have fragments "ab" and "bc". Then pred: b->a? Actually from "ab": a->b, so pred[b]=a. From "bc": b->c? Wait "bc" gives b->c, pred[c]=b. So succ: a->b, b->c. pred: b->a, c->b. Nodes with no pred: a (since pred[a] none). Following from a yields a,b,c. So chain "abc". That's fine.
Suppose fragments "ab" and "cd". succ: a->b, c->d. pred: b->a, d->c. Starts: a and c. Chains: "ab", "cd". Concatenating yields "abcd" or "cdab". Both are valid because "ab" appears in "abcd" as first two, and "cd" as last two. In "cdab", "ab" appears at the end, "cd" at start. So valid.
Thus, the graph approach works.
But we must also consider the possibility that fragments impose that some letters must NOT be adjacent? For example, if we have fragments "ab" and "ac", that's conflict because a would have two successors. So input avoids.
Now, is it possible that some letters appear in multiple fragments but the pairwise edges are consistent, yet the fragments themselves might not appear as substrings if we only enforce pairwise edges? For a fragment of length > 2, we need all consecutive pairs to be adjacent. That's enforced. So it's fine.
But what about a scenario where we have fragments "abc" and "bcd"? That yields edges a->b, b->c, c->d. That's a chain a-b-c-d. So "abc" appears as positions 1-3, "bcd" as 2-4. Good.
Now, consider a fragment "ab" and a fragment "bc". Already considered.
Now, consider a fragment "ab" and a fragment "ac". Conflict, so no.
Thus, the problem reduces to constructing the string from forced adjacency edges.
However, we must also consider that fragments may be given that are substrings of each other. For example, fragment "abcd" and fragment "bc". The edges from "abcd" give a->b, b->c, c->d. Fragment "bc" gives b->c, which is consistent. So no problem.
Edge Cases: Letters might be many, but n ≤ 100, each string length? Not given but since distinct letters and 26 possible letters, max length per fragment is at most 26. So total letters ≤ 26. Actually there are only 26 possible distinct letters, since small English letters. So the genome length is at most 26. So we can brute force.
Thus, solution seems trivial: Build succ and pred from fragments, ensure no contradictions (but input says guaranteed), then find all nodes with no predecessor, follow succ to build chains, concatenate them in any order, output. That will give a string of distinct letters.
But is this always minimal length? Yes, because we must include all distinct letters, so length = number of distinct letters. Since any valid genome must contain all letters, the minimal length is exactly that. So any ordering that respects constraints yields a string of that length, so it's minimal.
But wait: Could there be a scenario where including all letters forces the string to be longer than the number of distinct letters? No, a string of distinct letters with each letter exactly once has length equal to the number of distinct letters. So it's minimal.
Thus, the answer is simply the concatenation of the forced chains.
Now, we need to be cautious: Is it guaranteed that after processing all fragments, the forced edges cover all letters? Possibly some letters have no edges; they are isolated. They will appear as singleton chains.
We must also ensure that we don't have missing letters: letters that appear in fragments but not in any edge? They will be isolated.
But is there any scenario where some letter appears in edges but is not included in the start-follow process? We'll cover all.
Now, the order of concatenating chains: Since any order yields a valid genome, we can just output them in the order we find starts, e.g., sorted by start character or any. But must ensure that this ordering does not create unintended adjacency that might break some fragment? As argued, fragments are within chains, so no. But consider a fragment that is exactly the concatenation of two chains? That would require an edge between the last of first chain and first of second chain, which would merge them. So not possible.
Thus, answer is deterministic? Not necessarily, but any order works.
Now, let's test with provided examples.
Example 1:
3
bcd
ab
cdef
Letters: b,c,d,a,b,c,d,e,f? Actually distinct: a,b,c,d,e,f.
Process:
bcd: edges: b->c, c->d.
ab: a->b.
cdef: c->d (already exists? Wait from bcd we have c->d, but cdef gives c->d and d->e, e->f. So edges: c->d (consistent), d->e, e->f.
So succ: a->b, b->c, c->d, d->e, e->f. pred: b->a, c->b, d->c, e->d, f->e.
Starts: a (no pred). Follow: a,b,c,d,e,f -> "abcdef". Output matches.
Example 2:
4
x
y
z
w
All length 1, no edges. All letters: x,y,z,w. No pred for each. So starts: x,y,z,w (assuming we iterate over set, order maybe alphabetical or as inserted). Any order yields a string of length 4. Output "xyzw" in example. Could be any permutation. So it's okay.
Now, test a more complex scenario: Suppose fragments: "ab", "bc", "cd". Edges: a->b, b->c, c->d -> chain "abcd". Good.
Suppose fragments: "ab", "de", "bd". That would be edges: a->b, d->e, b->d. Then pred: b->a, e->d, d->b? Wait b->d gives succ[b]=d, pred[d]=b. But also d has succ e, so d->e. So we have: a->b->d->e. Starts: a (no pred). So chain "abde". This string includes "ab", "de" as substrings? "ab" at start, "de" at positions 3-4? Actually "abde": positions: 1:a,2:b,3:d,4:e. "de" appears at positions 3-4, yes. "bd" appears at positions 2-3? b and d are not adjacent? Actually "bd" would require b followed by d. In "abde", b is at position 2, d at position 3, so they are adjacent? Yes, b then d, so "bd" is substring (positions 2-3). So good. So edges consistent.
Now, what if we had "ab", "bc", and also "ac"? That would give a->b, b->c, and a->c. Conflict because a would have two successors (b and c). So input not allowed.
Thus, solution seems straightforward.
But wait, is it always true that the forced adjacency edges are sufficient to guarantee that the fragments appear as substrings? Suppose we have fragment "abc". Edges: a->b, b->c. That ensures a,b,c are consecutive. But what if we have fragments "ab" and "bc", but we also have fragment "ac"? Actually "ac" is not a substring of "abc"? In "abc", "ac" is not a substring because a and c are not adjacent. So if the input had fragments "ab", "bc", and "ac", that would be contradictory because "ac" would require a and c to be adjacent, but with a->b and b->c, a and c are not adjacent (they have b between). So that would be inconsistent. But our model would have edges a->b, b->c from "ab" and "bc", and from "ac" we would have edge a->c, which conflicts with a->b. So it would be detected as conflict. Good.
But consider a fragment that is longer than the chain? Actually all fragments must be substrings, so they must be contiguous subsequences of the genome. The forced adjacency edges from that fragment will guarantee that the letters appear consecutively in that order. However, what about fragments that are not a contiguous block in the chain because there might be extra letters between them due to other forced edges? But forced edges from the fragment itself ensure that there are no extra letters between them, because they enforce immediate adjacency. But what if there are other fragments that cause some of those letters to have additional successors/predecessors? That would conflict.
Thus, fine.
Now, we must also consider that the genome must contain each fragment as a substring exactly as given, but it does not require that the fragment appears only in one way; as long as it appears somewhere. So our construction works.
Thus, the algorithm is simple.
But is there any scenario where the set of maximal chains built from succ/pred does not yield a valid string because the relative order of chains might be constrained by fragments that are not captured by edges? For example, consider fragments "ab" and "bc". Already covered. Consider fragments "abc" and "b". No problem.
Consider fragments "ab" and "cd". No constraints between chains. So any order works. But could there be an implicit constraint from the fact that the fragment "ab" must appear as a substring, and the fragment "cd" must appear as a substring, but if we put "cd" before "ab", does "ab" appear? In "cdab", "ab" appears at the end, yes. So fine.
Thus, any order works.
Now, about minimal length: Since we include all distinct letters, the length is minimal. So output string length equals number of distinct letters.
Now, we need to output the genome. So we just output concatenation of chains.
But wait, is it always possible to just concatenate the chains arbitrarily? Could there be a case where a fragment is not exactly a chain but spans across the boundary of two chains if we concatenate them in a certain order? That would mean the fragment's letters are split across two chains, but if that happens, then the fragment would not be contiguous in the concatenated string because chains themselves are contiguous blocks, but the fragment's letters would be in two different blocks, and between blocks there is no guarantee of adjacency. However, if the fragment's letters are in two different chains, then the fragment would require adjacency between the last letter of one chain and the first letter of the other chain. That adjacency would be an edge, which would have merged the chains. So they cannot be in different chains. Therefore, any fragment's letters are all within a single chain. So ordering doesn't affect its contiguity.
Thus, the solution is correct.
Now, we must be careful with building succ and pred: When we process each fragment, we add edges for consecutive pairs. However, we must also ensure that we don't inadvertently create a situation where a node gets two different predecessors or successors. Input guarantees no conflict, but we may still check to be safe.
After building, we also need to detect if there is a cycle. Even if there is no conflict, a cycle could exist if we have e.g., a->b, b->c, c->a. That would mean each node has indegree=outdegree=1, but no node with indegree 0. In our algorithm, we would have no start nodes, but we would still have letters. That would be invalid because we can't order them linearly while preserving adjacencies (a cycle would require the string to be circular). Since the problem guarantees existence, we assume no cycles.
But we can handle cycles by breaking them? Not needed.
Now, we must ensure that we include all letters: from fragments, we collect all characters.
Implementation steps:
-
Use a dict (or array of size 26) for succ and pred, initialized to None or -1.
-
Also maintain a set of all letters.
-
For each string s:
- For i in range(len(s)-1):
a = s[i]; b = s[i+1];
if succ[a] is not None and succ[a] != b: conflict (should not happen)
if pred[b] is not None and pred[b] != a: conflict
succ[a] = b; pred[b] = a
-
After building, we need to generate the string:
- For each letter (character) that has pred[letter] is None, start a chain.
- But careful: Some letters may be part of a chain but not be a start because they have a predecessor. But we must also cover letters that are in a cycle (if any) - but guaranteed none.
- Also, letters that are isolated (no pred and no succ) will be chains of length 1.
However, there is a subtlety: What if a letter has a predecessor but we later start from a letter with no predecessor and follow succ, we will eventually reach it. But if there is a letter with a predecessor but not reachable from any start, that would indicate a cycle or a chain that is not rooted (but if no start, it's a cycle). So we need to ensure we cover all letters. After processing starts and following succ, we may have some letters not visited because they belong to a cycle (no start). Since problem guarantees existence, but just in case, we could also start from any unvisited letter if cycle exists, but then we have to break the cycle arbitrarily? Not needed.
But note: There could be a chain that has no start? That would be a cycle. But given constraints, probably not.
-
While following succ, we should be careful that we don't follow into a visited node. Since the graph is a collection of disjoint paths, no node will be visited twice.
-
After generating chains, we can concatenate them in any order. But is there any ordering that could be invalid? Consider two chains: Chain1 = "ab", Chain2 = "cd". Suppose there is a fragment "bc"? That would have merged them. So fine.
However, there is a nuance: Suppose we have two chains: "ab" and "bc". Wait "ab" and "bc" would have merged because b is in both? Actually if we have "ab" and "bc", b is common? In "ab", b is at end; in "bc", b is at start. That would cause b to have succ from "ab"? "ab" gives a->b, but b has no succ from that fragment. "bc" gives b->c, so b gets succ c, and pred from a? Actually b's pred from "ab" is a. So b has pred a and succ c, so it's in the middle of a chain a-b-c. So they are merged. So chains are disjoint sets of nodes.
Thus, we can safely output concatenation in any order. To produce a deterministic output, we could sort the start nodes lexicographically, or just process letters in alphabetical order. But we need to ensure that the output is of minimal length and valid. The example output "xyzw" is in alphabetical order? x,y,z,w is alphabetical? Actually alphabetical would be w,x,y,z. But they output xyzw. So not necessarily alphabetical. But any order works.
But we must be cautious: The problem states "If there are multiple such strings, choose any string." So we can output any.
Now, before finalizing, let's think if there are any hidden constraints or tricky cases.
Edge Cases:
-
Single fragment: e.g., "abc". Then edges: a->b, b->c. Starts: a. Chain "abc". Output "abc". That's correct.
-
Multiple fragments overlapping partially: e.g., fragments: "abc", "bcd", "cde". Edges: a->b, b->c, c->d, d->e. Chain "abcde". Output that.
-
Fragments that are substrings of each other: e.g., "abcd", "bc". Edges: a->b, b->c, c->d from first; b->c from second. Chain "abcd". Good.
-
Fragments that are completely separate: "ab", "cd". Chains "ab", "cd". Output either "abcd" or "cdab". Both valid.
-
Letters not in any adjacency: e.g., fragments: "a", "b", "c". No edges. Chains: each letter isolated. So we can output any permutation, e.g., "abc". That works.
-
Mix of edges and isolated: e.g., fragments: "ab", "c". Edges: a->b. Chain "ab", and isolated c. So we need to output "abc" or "cab" or "acb"? Wait, can we place c between a and b? If we put "acb", then "ab" is not a substring because a and b are not adjacent. So we must keep a and b adjacent. So c cannot be inserted between a and b. So c must be placed either before a or after b. So chains: "ab" is a block, c is isolated. So the valid orderings are "cab" or "abc". So our method of concatenating chains: we have chain "ab" and chain "c". If we output "abc" (chain "ab" then "c") -> "ab" is substring (positions 1-2), c appears, good. If we output "cab" -> "ab" is substring positions 2-3, good. If we output "acb" that would interleave, but our method of concatenating chains as whole blocks ensures we don't interleave. So it's safe. Good.
Thus, concatenating chains as blocks is necessary; we cannot arbitrarily permute individual letters because that might break adjacency constraints. So we must treat each maximal path as a block.
Now, we need to produce the string by outputting the blocks in some order. As argued, any order works.
But is it always safe to output blocks in any order? Let's test a scenario: Suppose we have three blocks: Block1 = "ab", Block2 = "cd", Block3 = "ef". All fragments are within blocks. No fragments span across blocks. So any concatenation works.
Now, consider a scenario where there is a fragment that is exactly one block but also a fragment that is a substring that includes letters from two blocks? That would be a cross-block fragment, which would have forced edges connecting the blocks, merging them. So not possible.
Thus, any order of blocks yields a valid genome.
But wait, what about fragments that are length 1? They are just single letters. Those letters may appear in a block (if they have adjacency) or be isolated. If they are in a block, they are part of a chain. If they are isolated, they are singleton blocks. No issue.
Now, what about fragments that are longer but their letters are not all in the same block because they are not fully connected by edges? For a fragment to be a substring, its letters must appear consecutively in the genome. In our block concatenation, each block is a contiguous sequence of letters with forced adjacencies between consecutive letters. If a fragment's letters are not all in one block, then they are split across multiple blocks. Since between blocks there is no forced adjacency (we can place blocks adjacent to each other, but the fragment's letters would be separated by the boundary between blocks). For the fragment to be a substring, the letters must appear consecutively. If they are split across two blocks, then at the boundary, the last letter of the first block and the first letter of the second block become adjacent in the concatenated string. So if the fragment includes that adjacency, then it would require an edge between those two letters. But that edge would have merged the blocks. So if there is no edge, the fragment cannot be a substring if its letters are split across blocks unless the concatenation order happens to place the blocks such that the fragment's letters become contiguous across the boundary? Let's examine: Suppose we have two blocks: Block1 = "ab", Block2 = "cd". If we have a fragment "bc", that would require b and c to be adjacent. If we concatenate Block1 then Block2 as "abcd", then b and c become adjacent, so "bc" is a substring. But does the fragment "bc" exist? If it does, then there should be an edge b->c, which would have merged the blocks. So in our graph, if fragment "bc" exists, we would have added edge b->c, merging Block1 and Block2 into a single block "abcd". So after processing, blocks would be "abcd". So indeed, if a fragment spans across what would otherwise be two blocks, the edge would exist and they would be merged. Therefore, after processing all fragments, the maximal paths (blocks) are such that no fragment's letters are split across blocks because any adjacency required by a fragment is represented as an edge, which would connect the blocks.
But what about a fragment of length > 2 that spans across blocks without requiring adjacency between the last of block1 and first of block2? For example, fragment "abc". Suppose we have blocks: "ab" and "c". For "abc" to be a substring, we need a,b,c consecutively. In concatenation "abc" (block "ab" then block "c"), we get a,b,c consecutively. But does that require edge b->c? Yes, because "abc" includes adjacency b->c. So if fragment "abc" exists, we would have edge b->c, which would merge "ab" and "c" into "abc". So blocks would be merged.
If we instead concatenate as "cab", then "abc" is not a substring. So the existence of fragment "abc" forces the edge b->c, thus merging blocks. So after processing, blocks reflect all required adjacencies.
Thus, any valid ordering of blocks would satisfy all fragments? Not necessarily: Consider blocks that are not connected by edges, but a fragment might be a substring that appears only if blocks are concatenated in a specific order? For a fragment to be a substring, its letters must appear consecutively. If the fragment's letters are all within a single block, then regardless of where that block is placed, the fragment appears as a substring within that block. However, the block itself is contiguous, but if we place other blocks before or after, the fragment still appears as a substring. So it's fine.
But could there be a fragment that consists of the concatenation of two blocks in a specific order, but not the reverse? For example, suppose we have blocks "ab" and "c". If there is a fragment "abc", then as argued, there would be edge b->c, merging them into "abc". So not separate.
What if there is a fragment "cab"? That would require c->a edge, merging c and a. So they'd be merged.
Thus, after processing, the blocks are maximal with respect to the forced edges. So fragments are substrings within blocks, not across block boundaries.
Therefore, any ordering of blocks yields a valid genome.
But wait: Could there be a scenario where a fragment is exactly a block, but the block might appear in the genome in a reversed order? No, blocks have fixed order because of directed edges.
Thus, the answer is simply the concatenation of all maximal paths (chains) in any order.
Now, what about letters that are part of a cycle? As argued, input guarantees no cycles, but let's think if a cycle could be valid? Suppose we have fragments "ab", "bc", "ca". That would require a->b, b->c, c->a. In a string of distinct letters, can we have a->b, b->c, c->a? That would imply a followed by b, b by c, c by a. Since letters are distinct, the only way is if the string is something like a,b,c,... but then a cannot also follow c unless a repeats. So impossible. So cycles invalid.
Now, the algorithm seems straightforward.
But before finalizing, let's test with some random cases.
Case: fragments: "ab", "ac". Conflict, but input says not possible.
Case: fragments: "abc", "cde". Edges: a->b, b->c, c->d, d->e. That yields chain "abcde". Fine.
Case: fragments: "ab", "bc", "cd", "de". Chain "abcde".
Case: fragments: "ab", "bc", "bd". That would give a->b, b->c from first two, and b->d from third, conflict: b has two successors. So not possible.
Case: fragments: "ab", "bc", "abc". That's fine: edges a->b, b->c. Chain "abc". Fragment "abc" is substring.
Now, more complex: fragments: "ab", "bc", "cd", "ef", "fg". So two chains: "abcd" and "efg". Any order works.
Now, consider also fragments that are substrings of each other but with extra letters: e.g., "abc", "b". That's fine.
Thus, solution is clear.
Now, we need to implement.
Implementation details:
- We'll use arrays of size 26 for succ, pred, visited.
- Also, a boolean array used to mark letters present.
- For each string s:
- For each character in s, mark present.
- For i from 0 to len(s)-2:
let a = s[i], b = s[i+1].
if succ[a] is already set and succ[a] != b: conflict (maybe output something? but problem guarantees no conflict, so we can ignore or assert).
if pred[b] is already set and pred[b] != a: conflict.
set succ[a]=b, pred[b]=a.
- After building, we need to collect all letters present (set).
- Then find all letters with pred[letter] == 0 (or None). We'll treat None as 0 or -1. Since we use array of chars, we can store -1 for none.
- For each such start, follow succ to build a string, appending each char, and mark visited.
- After processing all starts, there might be letters not visited (if there is a cycle, but guarantee not). But just in case, we can also handle cycles by picking any unvisited and following? But we trust input.
- Finally, concatenate all built strings in some order. We can sort starts alphabetically to have deterministic output, or just process in order of appearance. But need to ensure that the output is of minimal length and valid.
Potential pitfalls: The input may contain duplicate fragments, but that's fine.
Now, confirm with example: Input 1 yields "abcdef". That's what we get if we start from 'a' (only start). Good.
Edge case: Suppose there are multiple starts. For instance, fragments: "ab", "cd". Pred: b has pred a, d has pred c. Starts: a and c. Following