So what *is* allowed? Can you have 'a|b' => 'b|c'? Can you have 'a|b' => 'b|a'? Can you have 'a|b|c' => 'x|y'? 'a|b' => 'x|y|z'? Be more specific on the constraints. (Your constraints will make the difference between a cubed, O(n log n) or a linear solution, so they are important).