<p>I use this question in interviews and I wonder what the best solution is.</p>

<p>Write a Perl sub that takes <em>n</em> lists, and then returns 2^<em>n</em>-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that <em>n</em> is reasonably small (less than 20).</p>

<p>For example:</p>

<pre><code>list_compare([1, 3], [2, 3]);
  =&gt; ([1], [2], [3]);
</code></pre>

<p>Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.</p>

<pre><code>list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7])
  =&gt; ([1], [2], [3], [4], [5], [6], [7])
</code></pre>

<p>Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.</p>

<p>I usually give this problem as a follow up to the subset of this problem for <em>n</em>=2.</p>

<p>What is the solution? </p>

<p>Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does.</p>

[{'answer_id': 68417, 'author': 'nohat', 'author_id': 3101, 'author_profile': 'https://Stackoverflow.com/users/3101', 'pm_score': 0, 'selected': False, 'text': '<p>Here is my solution:</p>\n\n<p>Construct a hash whose keys are the union of all the elements in the input lists, and the values are bit strings, where bit <em>i</em> is set if the element is present in list <em>i</em>. The bit strings are constructed using bitwise or. Then, construct the output lists by iterating over the keys of the hash, adding keys to the associated output list.</p>\n\n<pre><code>sub list_compare {\n    my (@lists) = @_;\n    my %compare;\n    my $bit = 1;\n    foreach my $list (@lists) {\n        $compare{$_} |= $bit foreach @$list;\n        $bit *= 2; # shift over one bit\n    }\n\n\n    my @output_lists;\n    foreach my $item (keys %compare) {\n        push @{ $output_lists[ $compare{$item} - 1 ] }, $item;\n    }\n\n    return \\@output_lists;\n\n}\n</code></pre>\n\n<p>Updated to include the inverted output list generation suggested by Aristotle</p>\n'}, {'answer_id': 70024, 'author': 'user11318', 'author_id': 11318, 'author_profile': 'https://Stackoverflow.com/users/11318', 'pm_score': 1, 'selected': False, 'text': "<p>First of all I would like to note that nohat's answer simply does not work.  Try running it, and look at the output in Data::Dumper to verify that.</p>\n\n<p>That said, your question is not well-posed.  It looks like you are using sets as arrays.  How do you wish to handle duplicates?  How do you want to handle complex data structures?  What order do you want elements in?  For ease I'll assume that the answers are squash duplicates, it is OK to stringify complex data structures, and order does not matter.  In that case the following is a perfectly adequate answer:</p>\n\n<pre><code>sub list_compare {\n  my @lists = @_;\n\n  my @answers;\n  for my $list (@lists) {\n    my %in_list = map {$_=&gt;1} @$list;\n    # We have this list.\n    my @more_answers = [keys %in_list];\n    for my $answer (@answers) {\n      push @more_answers, [grep $in_list{$_}, @$answer];\n    }\n    push @answers, @more_answers;\n  }\n\n  return @answers;\n}\n</code></pre>\n\n<p>If you want to adjust those assumptions, you'll need to adjust the code.  For example not squashing complex data structures and not squashing duplicates can be done with:</p>\n\n<pre><code>sub list_compare {\n  my @lists = @_;\n\n  my @answers;\n  for my $list (@lists) {\n    my %in_list = map {$_=&gt;1} @$list;\n    # We have this list.\n    my @more_answers = [@$list];\n    for my $answer (@answers) {\n      push @more_answers, [grep $in_list{$_}, @$answer];\n    }\n    push @answers, @more_answers;\n  }\n\n  return @answers;\n}\n</code></pre>\n\n<p>This is, however, using the stringification of the data structure to check whether things that exist in one exist in another.  Relaxing that condition would require somewhat more work.</p>\n"}, {'answer_id': 70741, 'author': 'Aristotle Pagaltzis', 'author_id': 9410, 'author_profile': 'https://Stackoverflow.com/users/9410', 'pm_score': 2, 'selected': False, 'text': '<p>Your given solution can be simplified quite a bit still.</p>\n\n<p>In the first loop, you can use plain addition since you are only ever ORing with single bits, and you can narrow the scope of <code>$bit</code> by iterating over indices. In the second loop, you can subtract 1 from the index instead of producing an unnecessary 0th output list element that needs to be <code>shift</code>ed off, and where you unnecessarily iterate m*n times (where m is the number of output lists and n is the number of unique elements), iterating over the unique elements would reduce the iterations to just n (which is a significant win in typical use cases where m is much larger than n), <em>and</em> would simplify the code.</p>\n\n<pre><code>sub list_compare {\n    my ( @list ) = @_;\n    my %dest;\n\n    for my $i ( 0 .. $#list ) {\n        my $bit = 2**$i;\n        $dest{$_} += $bit for @{ $list[ $i ] };\n    }\n\n    my @output_list;\n\n    for my $val ( keys %dest ) {\n        push @{ $output_list[ $dest{ $val } - 1 ] }, $val;\n    }\n\n    return \\@output_list;\n}\n</code></pre>\n\n<p>Note also that once thought of in this way, the result gathering process can be written very concisely with the aid of the <a href="http://search.cpan.org/perldoc?List::Part" rel="nofollow noreferrer">List::Part</a> module:</p>\n\n<pre><code>use List::Part;\n\nsub list_compare {\n    my ( @list ) = @_;\n    my %dest;\n\n    for my $i ( 0 .. $#list ) {\n        my $bit = 2**$i;\n        $dest{$_} += $bit for @{ $list[ $i ] };\n    }\n\n    return [ part { $dest{ $_ } - 1 } keys %dest ];\n}\n</code></pre>\n\n<p>But note that <code>list_compare</code> is a terrible name. Something like <code>part_elems_by_membership</code> would be much better. Also, the imprecisions in your question Ben Tilly pointed out need to be rectified.</p>\n'}]
['https://Stackoverflow.com/questions/68352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3101/']