3

Each set contains bunch of checksums. For example:
Set A:
{
4445968d0e100ad08323df8c895cea15
a67f8052594d6ba3f75502c0b91b868f
07736dde2f8484a4a3af463e05f039e3
5b1e374ff2ba949ab49870ca24d3163a
}

Set B:
{
6639e1da308fd7b04b7635a17450df7c
4445968d0e100ad08323df8c895cea15
a67f8052594d6ba3f75502c0b91b868f
}

The maximum common subset of A and B is:
{
4445968d0e100ad08323df8c895cea15
a67f8052594d6ba3f75502c0b91b868f
}

A lot of these operations will be performed, so I'm looking for an efficient algorithm to do so. Thanks for your help.

P Shved
  • 96,026
  • 17
  • 121
  • 165
datasunny
  • 281
  • 1
  • 4
  • 14
  • 8
    What you want is called the intersection of the sets. – Daniel Newby Mar 09 '10 at 01:52
  • 1
    I've assumed in my answer that you're handling large sets. If you're handling large numbers of small sets, your approach will be a lot simpler - just sort the sets and then iterate the two in-step. –  Mar 09 '10 at 09:20

4 Answers4

8

Put one of the sets in a hash table and iterate through the other, discarding elements that aren't in the hash. Alternatively, sort both and iterate through them simultaneously, as in merge sort.

EDIT: The latter method creates a sorted result. I should add that if the sets are of widely disparate sizes and they're presorted (say because you're doing a bunch of intersections), then you can realize a large performance improvement by using "unbounded" binary search to skip ahead in the large list.

user287792
  • 1,581
  • 9
  • 12
6

Stick them in a hashtable and note the exact collisions.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2
  1. Add Set A to a structure where you can find if a checksum exists.
  2. Loop Set B, check if element exists in Set A, if it exists, add to Set C

Set C is your common subset.

Carlos Gutiérrez
  • 13,972
  • 5
  • 37
  • 47
0
  • Make ordered vector/list A from Set A
  • Make ordered vector/list B from Set B
  • Iterate over ordered A,B making new step on smaller element - if identical, add to restult and move both.

When underlying set structure is ordered - common case is a kind of Tree (BST,AVL etc.), - then you need only last step to perform.

To make last step clear, here is it's pseudocode:

a = A.begin(); b = B.begin();
while(a!=A.end() && b!=B.end()){
  if(*a==*b){
    results.add(a);
    ++a; ++b;
  } else if(*a < *b) {
    ++a;
  } else {
    ++b;
  }
}
Grzegorz Wierzowiecki
  • 10,545
  • 9
  • 50
  • 88