This can be solved using the Topological Sort algorithm.
If you consider each of your input sequences as a path through a directed graph, topological sorting will arrange your set of nodes from left to right so that each directed edge points to the right. 
The topological sorting wikipedia page includes this algorithm, first described by Arthur Kahn in 1962:
L β Empty list that will contain the sorted elements S β Set of all nodes with no incoming edges while S is non-empty do remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S if graph has edges then return error (graph has at least one cycle) else return L (a topologically sorted order)
This algorithm, as written, does not actually work if it finds ambiguous sequences, but it is easy to add by inserting a check at the beginning of the loop, for example:
... while S is non-empty do if S contains more than 1 item return error (inputs are ambiguous) remove a node n from S ...
I donβt know what language you work in, but I chose this PHP implementation as proof of concept:
function mergeSequences($sequences, $detectAmbiguity = false) {
You can call the function as follows:
$input = array( array('XS', 'M', 'L', 'XL'), array('S', 'M', 'XXL'), array('XXS', 'XS', 'S', 'L'), ); echo(join(', ', mergeSequences($input))); echo(join(', ', mergeSequences($input, true)));
To get the following output:
XXS, XS, S, M, XXL, L, XL Uncaught exception 'Exception' with message 'Ambiguous sequence: M can be followed by L or XXL'