UVa 10252 - Common Permutation

10252 - Common Permutation

 * http://acm.uva.es/p/v102/10252.html

Summary
Given two strings a and b, We have to find the largest string x such that there is a permutation of x that is a subsequence (NOT substring) of a and another permutation of x (likely distinct) which is a subsequence of b. If there is more than one such string x, output the lexicographically smallest one.

Explanation
This problem is actually very easy to code, after you have a little bit of insight. Rather than considering the input strings as strings, consider them a multiset of characters. Let y be any string, and let Y be the multiset of characters produced from y. Then it is clear that any subset Z of Y, when transformed as a string z, has some permutation that is a subsequence of y. That may sound complicated, but all it really means is that "u is a subseqence of v" is preserved as we remove characters from u. Now consider both strings a and b as multisets A and B. The largest multiset which is a subset of both A and B is the intersection of A and B.

To solve this problem, simply compute the intersection of a and b, and output it in sorted order.

Gotcha's

 * There may be empty lines in the input.

Input
pretty women walking down the street

pairedwithblank theoutputfortheabovetestcaseshouldbeblank becauseitispairedwithablank

Output
e nw et

aabbcdeeehloopssuv